TypeError: only size1 arrays can be converted to Python scalars
Dung Do Tien
Aug 10 2021
344
Hello, I just only a newbie in Python, and I'm studying the array and now I want to print out all items of it to console.
import numpy as np
y = np.array([1, 2, 3, 4, 5, 6, 7, 8])
y = np.float(y)
print(y)
But when I run this code I get the error "TypeError: only size1 arrays can be converted to Python scalars"
main.py:4: DeprecationWarning: `np.float` is a deprecated alias for the builtin `float`. To silence this warning, use `float` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.float64` here.
Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0notes.html#deprecations
y = np.float(y)
Traceback (most recent call last):
File "main.py", line 4, in <module>
y = np.float(y)
TypeError: only size1 arrays can be converted to Python scalars
How can I resolve this issue?
Have 3 answer(s) found.

D0
Dương Trang Quốc Aug 10 2021
You can use Loops to help print out items of an array
Loops are the most brute force methods to apply a function over a set of values. But it provides us control over all parts of the elements and can be used to customize elements if we need it.
import numpy as np x = np.array([1, 2, 3, 4, 5, 6, 7]) y = np.array([None]*6) for i in range(6): y[i] = np.float(x[i]) print(y)

N0
Nitin Kumar Aug 10 2021
You can use Map() function as below:
import numpy as np x = np.array([1, 2, 3, 4, 5, 6]) x = np.array(list(map(np.float, x))) print(x)

T0
Thắng Ngô Minh Aug 10 2021
You can try using
vectorize()
method.import numpy as np vector = np.vectorize(np.float) x = np.array([1, 2.56, 3, 4, 5.5, 6, 7.4]) x = vector(x) print(x)
It's worked for me!!
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.