K. Kovalev K. Kovalev - 7 months ago 614
Python Question

TypeError: only length-1 arrays can be converted to Python scalars while plot showing

I have such Python code:

import numpy as np
import matplotlib.pyplot as plt

def f(x):
return np.int(x)

x = np.arange(1, 15.1, 0.1)
plt.plot(x, f(x))
plt.show()


And such error:

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


How can I fix it?

Answer

np.int expects a single value not a list since it cannot convert a list/array to an integer. If you want to convert each element in that array, you can use np.vectorize to vectorize your function:

import numpy as np
import matplotlib.pyplot as plt

def f(x):
    return np.int(x)
f2 = np.vectorize(f)
x = np.arange(1, 15.1, 0.1)
plt.plot(x, f2(x))
plt.show()

Note: You can skip the definition of f(x) and just pass np.int to the vectorize function: f2 = np.vectorize(np.int).

Comments