TypeError: only siz...
Notifications
Clear all

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

RSS

(@sathish)
Member Moderator
Joined: 2 years ago
Posts: 1391
12/05/2021 12:28 pm

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

这样的错误:

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

How can I fix it?


Quote
(@anamika)
Noble Member
Joined: 2 years ago
Posts: 1381
12/05/2021 12:29 pm

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 ofnp.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 usenp.vectorizesee 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()


ReplyQuote
Share:
Baidu