gpt4 book ai didi

python - 类型错误 : only length-1 arrays can be converted to Python scalars while plot showing

转载 作者:IT老高 更新时间:2023-10-28 20:45:12 27 4
gpt4 key购买 nike

我有这样的 Python 代码:

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

我该如何解决?

最佳答案

当函数需要单个值但您传递一个数组时,会引发错误“只有长度为 1 的数组可以转换为 Python 标量”。

np.int 是内置 int 的别名,在 numpy v1.20 中已弃用。 int 的参数应该是一个标量,它不接受类似数组的对象。一般来说,如果你想对数组的每个元素应用一个函数,你可以使用 np.vectorize :

import numpy as np
import matplotlib.pyplot as plt

def f(x):
return int(x)
f2 = np.vectorize(f)
x = np.arange(1, 15.1, 0.1)
plt.plot(x, f2(x))
plt.show()

您可以跳过 f(x) 的定义,只需将函数 int 传递给 vectorize 函数:f2 = np.vectorize(int)

请注意,np.vectorize 只是一个便利函数,基本上是一个 for 循环。这在大型阵列上效率低下。只要有可能,请使用真正矢量化的函数或方法(例如 astype(int) as @FFT suggests )。

关于python - 类型错误 : only length-1 arrays can be converted to Python scalars while plot showing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36680402/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com