How to fix only size-1 arrays can be converted to python scalars

How to fix only size-1 arrays can be converted to python scalars

With this error faces programmers that work with numpy packet when try to use int conversion to numpy array.

For solving this issue you can use astype(int) function from numpy module.

import numpy

n_array = numpy.arange(1, 4.5, 0.1)
print("Initial list:")
print(n_array)

try:
    numpy.int(n_array)
except TypeError as e:
    print(f"Error: {e}")

print("Converted list:")
print(n_array.astype(int))

Output:

Initial list:
[1.  1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2.  2.1 2.2 2.3 2.4 2.5 2.6 2.7
 2.8 2.9 3.  3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 4.  4.1 4.2 4.3 4.4]
Error: only size-1 arrays can be converted to Python scalars
Converted list:
[1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4]
#python
0
Roman Ivashchenko profile picture
Dec 11, 2020
by Roman Ivashchenko
Did it help you?
Yes !
No

Best related

Other by Roman Ivashchenko