0 votes
in Python by

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

TypeError: only size-1 arrays can be converted to Python scalars
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
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()

Related questions

+1 vote
asked Jan 10, 2021 in Python by rajeshsharma
0 votes
asked Jan 16, 2021 in Python by SakshiSharma
...