我的 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调用的签名,您会注意到它接受表中的相同值。一般来说,如果你想实现一个对作用域内的所有元素接受相同元素的函数,你可以使用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)
请注意,np.vectorize 只是循环的一个有用且通用的函数。它不如大型套件那么有效。如果可能,您应该拥有实时向量函数或方法(按轴类型 (int) @FFT推荐)。文章来源:https://www.toymoban.com/article/447.html
文章来源地址https://www.toymoban.com/article/447.html
到此这篇关于TypeError: only length-1 arrays can be converted to Python scalars的文章就介绍到这了,更多相关内容可以在右上角搜索或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!