Typeerror: only length-1 arrays can be converted to python scalars
Dung Do Tien
Mar 23 2021
311
Hello, I have some code with Python as below:
import numpy as np
import matplotlib.pyplot as pyp
def find(x):
return np.int(x)
x = np.arange(1, 15.1, 0.1)
pyp.plot(x, find(x))
pyp.show()
When I running this code, I got an error Typeerror: only length-1 arrays can be converted to Python scalars.
How can I fix this bug?
Have 1 answer(s) found.
-
J-1
Jide Mar 23 2021
This error is raised when the function expects a single value but you pass an array instead.
If you want to apply a function that accepts a single element to every element in an array, you can use
np.vectorize
:import numpy as np import matplotlib.pyplot as pyp def f(x): return np.int(x) v = np.vectorize(f) x = np.arange(1, 15.1, 0.1) pyp.plot(x, v(x)) pyp.show()
I hope it helpful for you.
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.