Online Tutorials & Training Materials | STechies.com
Register Login

TypeError: Only Size-1 Arrays Can be Converted to Python Scalars

19 Sep 2019 11:17 am || 0

While using numpy and matplotlib libraries in Python, you might need to use functions that take single values to perform an operation. But in case you pass an array instead of a single value to this function, it will throw an error. You are likely to encounter a Python TypeError Only Size-1 Arrays Can be Converted to Python Scalars.

Example:

# import numpy & matplotlib
import numpy
import matplotlib.pyplot

# define your custome function
def myfunction(x):
  return numpy.int(x)

#
#myfunction2 = numpy.vectorize(myfunction)

x = numpy.arange(1, 15.1, 0.1)
matplotlib.pyplot.plot(x, myfunction(x))
matplotlib.pyplot.show()

Output:

Traceback (most recent call last):
  File "error-1.py", line 13, in <module>
    matplotlib.pyplot.plot(x, myfunction(x))
  File "error-1.py", line 7, in myfunction
    return numpy.int(x)
TypeError: only size-1 arrays can be converted to Python scalars

Solution:

As you can see in the above example we have called single int(x) value in the function and for value of ‘x’ we are passing an array that is the reason we are getting this type error.

To fix this error we can use numpy.vectorize() function to convert an array in to vector.

# import numpy & matplotlib
import numpy
import matplotlib.pyplot

# define your custom function
def myfunction(x):
  return numpy.int(x)

myfunction2 = numpy.vectorize(myfunction)
x = numpy.arange(1, 15.1, 0.1)
matplotlib.pyplot.plot(x, myfunction2(x))
matplotlib.pyplot.show()

Output:

only size-1 arrays can be converted to python scalars

Conclusion

You must pass single values to functions that accept a single value. As mentioned earlier, the best way to solve this error is to use numpy.vectorize() method. This will convert the array you pass to the function, into a vector.