How to Fix: Only size-1 arrays can be converted to Python scalars


One error you may encounter when using Python is:

TypeError: only size-1 arrays can be converted to Python scalars

This error occurs most often when you attempt to use np.int() to convert a NumPy array of float values to an array of integer values.

However, this function only accepts a single value instead of an array of values.

Instead, you should use x.astype(int) to convert a NumPy array of float values to an array of integer values because this function is able to accept an array.

The following example shows how to fix this error in practice.

How to Reproduce the Error

Suppose we create the following NumPy array of float values:

import numpy as np

#create NumPy array of float values
x = np.array([3, 4.5, 6, 7.7, 9.2, 10, 12, 14.1, 15])

Now suppose we attempt to convert this array of float values to an array of integer values:

#attempt to convert array to integer values
np.int(x)

TypeError: only size-1 arrays can be converted to Python scalars 

We receive a TypeError because the np.int() function only accepts single values, not an array of values.

How to Fix the Error

In order to convert a NumPy array of float values to integer values, we can instead use the following code:

#convert array of float values to integer values
x.astype(int)

array([ 3,  4,  6,  7,  9, 10, 12, 14, 15])

Notice that the array of values has been converted to integers and we don’t receive any error because the astype() function is able to handle an array of values.

Note: You can find the complete documentation for the astype() function here.

Additional Resources

The following tutorials explain how to fix other common errors in Python:

How to Fix KeyError in Pandas
How to Fix: ValueError: cannot convert float NaN to integer
How to Fix: ValueError: operands could not be broadcast together with shapes

Leave a Reply

Your email address will not be published.