类型错误:只有长度为 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
我该如何解决?
推荐答案
only length-1 arrays can convert to Python scalars"错误当函数需要单个值但您传递一个数组时引发.
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
的调用签名,您会发现它接受单个值,而不是数组.一般来说,如果要将接受单个元素的函数应用于数组中的每个元素,可以使用 np.vectorize
:
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 传递给 vectorize 函数: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).
这篇关于类型错误:只有长度为 1 的数组可以在绘图显示时转换为 Python 标量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!