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