TypeError:只有长度为1的数组可以转换为Python标量,而绘图显示 [英] TypeError: only length-1 arrays can be converted to Python scalars while plot showing
问题描述
我有这样的Python代码:
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
我该如何解决?
推荐答案
当函数期望单个值但您传递一个数组时,将引发错误仅将length-1数组可以转换为Python标量".
The error "only length-1 arrays can be converted to Python scalars" is raised when the function expects a single value but you pass an array instead.
如果查看np.int
的呼叫签名,您会看到它接受单个值,而不是数组.通常,如果要对数组中的每个元素应用接受单个元素的函数,则可以使用
If you look at the call signature of np.int
, you'll see that it accepts a single value, not an array. In general, 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 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()
您可以跳过f(x)的定义,只需将np.int传递给矢量化函数:f2 = np.vectorize(np.int)
.
You can skip the definition of f(x) and just pass np.int to the vectorize function: f2 = np.vectorize(np.int)
.
请注意,np.vectorize
只是一个便捷功能,基本上是一个for循环.在大型阵列上这将是低效的.只要有可能,请使用真正的向量化函数或方法(例如astype(int)
,如 @FFT建议).
Note that np.vectorize
is just a convenience function and basically a for loop. That will be inefficient over large arrays. Whenever you have the possibility, use truly vectorized functions or methods (like astype(int)
as @FFT suggests).
这篇关于TypeError:只有长度为1的数组可以转换为Python标量,而绘图显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!