Typeerror: 크기가 1인 배열만 Python 스칼라로 변환할 수 있습니다. - 솔루션
이 튜토리얼은 Flexiple에서 자주 사용되거나 흥미로운 개념에 대한 짧은 큐레이트 튜토리얼을 작성하기 위한 이니셔티브의 일부입니다.
목차 - Typeerror: 크기가 1인 배열만 Python 스칼라로 변환할 수 있습니다.
"크기가 1인 배열만 Python 스칼라로 변환할 수 있음"은 무엇을 의미합니까?
You are likely to face the above typeerror while working with NumPy and matplotlib.pyplot. This error arises when you pass an array into a function that is expecting a single value (i.e., scalar value). Python generally works with only a handful of scalar values (Int, float, bool, etc) however while dealing with NumPy we have another 24 new fundamental Python types to describe different types of scalars. You can read more about them here .위의 오류로 인해 NumPy를 사용하는 동안 각별한 주의가 필요합니다. 내가 겪은 일반적인 오류는 다음과 같습니다.
import numpy as ny
import matplotlib.pyplot as matplot
def ycord(xcord):
return ny.int(xcord)
xcord = ny.arange(1, 5, 2.7)
matplot.plot(xcord, ycord(xcord))
matplot.show()
위의 입력에 대해 다음은 우리가 받는 출력입니다.
// Output
TypeError: only size-1 arrays can be converted to Python scalars
이것은 .int 함수가 단일 값만 받아들이고 우리의 경우 배열인 x를 전달하려고 하기 때문입니다.
솔루션 1: 코드 및 설명
In the first method, we use the .vectorize function. The .vectorize function is essentially a for loop that takes in an array and returns a single numpy array. Using this method we iterate over the array x and return a single value. Thus we do not encounter the "only size-1 arrays can be converted to Python scalars" typeerror.
import numpy as ny
import matplotlib.pyplot as matplot
xcord = ny.arange(1, 5, 2.5)
ycord = ny.vectorize(ny.int)
matplot.plot(xcord, ycord(xcord))
matplot.show()
As you can see we no longer need to define a function as we have used the .int function inside the .vectorize function, which loops through the array and returns a single array that is accepted by the .int function.
솔루션 2: 코드 및 설명
Another method I came across utilizes the .astype method, this method casts the array into a specified type in our case int. Although this method works, I personally recommend the first solution as this method casts a string into an int which is not a desirable method.
import numpy as ny
import matplotlib.pyplot as matplot
def ycord(xcord):
return xcord.astype(int)
xcord = ny.arange(1, 5, 2.5)
matplot.plot(xcord, ycord(xcord))
matplot.show()
These are two solutions that can be used when faced with the Typeerror: Only size-1 arrays can be converted to Python scalars error.
Do let me know your thoughts/ queries in the comment sections below. :)
Reference
이 문제에 관하여(Typeerror: 크기가 1인 배열만 Python 스칼라로 변환할 수 있습니다. - 솔루션), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/hrishikesh1990/typeerror-only-size-1-arrays-can-be-converted-to-python-scalars-solution-20o9텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)