Register Login

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

Updated Apr 22, 2020

A popular TypeError in Python is TypeError only length-1 arrays can be converted to python scalar. You might encounter when working with NumPy and Matplotlib libraries. This occurs when the function that you have defined or have created is expecting a single parameter but gets an array instead. You can start fixing this error by passing a single value to the function.

In this article, we will understand more about this error and its solution.

Example:

# Import numpy & matplotlib
import numpy
import matplotlib.pyplot

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

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

This error occurs as the function called np.int() takes in a single parameter as per its function definition. But if you are passing an array, it will not work and throw the error.

Solution:

Besides passing in a single element to the function you can also try using the np.vectorize() function. Use the following code to assign the np.int() method to this function:

# 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

The np.vectorize() function works as a "for loop" that allows the function passed into it to accept a single element from an array. So, a single element is passed onto the np.int() method every time.

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.  


×