且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

TypeError:只有长度为1的数组可以转换为Python标量,而绘图显示

更新时间:2022-02-14 18:44:05

当函数期望单个值但您传递一个数组时,将引发错误仅将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).