How can I fix the error “Only size-1 arrays can be converted to Python scalars”?

This error means that only one-dimensional arrays can be converted to a Python scalar, such as an integer or float. To fix this issue, you need to ensure that the array is one-dimensional and that the data type of each element is supported by Python. To do this, you can use the reshape function to change the shape of the array, or use the astype function to convert the elements to a supported data type.


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 .

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

x