0 votes
1 view
in Python by (30.9k points)

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?

1 Answer

0 votes
by (73.5k points)

You are getting the error "only length-1 arrays can be converted to Python scalars" is because when the function expects a single value instead of that you have passed an array.

Once you will look at the call signature of np.int, you'll see that it accepts a single value, not an array. 

Normally, if you want to apply a function that accepts a single element to every element in an array, you can use np.vectorize see the code below:-

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()

...