我的 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
如何解決這個問題?
解決方案
當函數(shù)需要相同的值時,會添加錯誤“僅將長度為 1 的表轉換為 Python 比例”,但您會傳遞該表。
如果您查看np.int調用的簽名,您會注意到它接受表中的相同值。一般來說,如果你想實現(xiàn)一個對作用域內的所有元素接受相同元素的函數(shù),你可以使用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 傳遞給向量函數(shù):f2 = np.vectorize(np.int)
請注意,np.vectorize 只是循環(huán)的一個有用且通用的函數(shù)。它不如大型套件那么有效。如果可能,您應該擁有實時向量函數(shù)或方法(按軸類型 (int) @FFT推薦)。文章來源:http://www.zghlxwxcb.cn/article/447.html
文章來源地址http://www.zghlxwxcb.cn/article/447.html
到此這篇關于TypeError: only length-1 arrays can be converted to Python scalars的文章就介紹到這了,更多相關內容可以在右上角搜索或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!