Only size-1 arrays can be converted to Python scalars How to fix it ( Easy Guide )

In this tutorial you will learn How to solve the following error Only size-1 arrays can be converted to Python scalars

Only size-1 arrays can be converted to python scalars

While working with Python you might come across the following error

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

You will come across this error when you try to convert NumPy array with float values to an array with integer values using  np.int() 

As this function only accepts single values instead of array .You should try to use  x.astype(int) for NumPy array of float to array of integer conversion as the function will accept an array.

Let’s see the solution below with an example

Reproducing the error

Let`s assume we have following NumPy array with float values

import numpy as np

x = np.array([3, 4.5, 6, 7.7, 9.2, 10, 12, 14.1, 15])

Now let’s try to convert the above provided array with float values to an array with integer values.

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

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

As we try to convert it to integer values we get a TypeError while the np.int() function only accepts single values instead of array .

Only size-1 arrays can be converted to python scalars How to Fix it

You can use the following function to convert NumPy array with float values to an array integer values


x.astype(int)

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

Once we use the above function astype(int) the array of values will be converterd to integers and you will not recieve the TypeError.

astype() function takes care of an array of values

 astype() function documentation

Only size-1 arrays can be converted to python scalars (Conclusion)

In the above tutorial we have provided you steps to fix the error Only size-1 arrays can be converted to python scalars.We hope this tutorial was helpful.

Related articles :

Best Python Courses 2021

Error 503 Backend fetch failed How to fix it ( Easy Essential Guide )