top of page

How to fix the error: "Only size-1 arrays can be converted to python scalar"?


This error occurs when the function expects a single value and not an array of values to convert.

Only size-1 arrays can be converted to python scalar

For example if we want to convert the following vector below.

import numpy as np
x = np.array([2, 3, 5, 7, 11, 13, 17, 19, 23])
print (np.int(x))

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

In order to get around this we can use the astype() function instead.

import numpy as np
x = np.array([2, 3, 5, 7, 11, 13, 17, 19, 23])

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

Note however that the x.astype(int) converts to integer values. If we want to keep any floating values in our array we should use the x.astype(float) instead.



Learn more about Python here for all my posts: https://www.pls-fix-thx.com/python

If you have found this article or website helpful. Please show your support by visiting the shop below.


81 views0 comments

Comments


bottom of page