我試圖將數據框傳遞給函數,並從數據框的不同列計算mean和std dev。當我逐步執行函數的每一行時(沒有像這樣寫函數),它工作正常。然而,當我嘗試寫一個函數來計算,我不斷收到此錯誤:TypeError:'float'對象在函數中沒有屬性'__getitem__'
TypeError: 'float' object has no attribute '__getitem__'
這是我的代碼:
def computeBias(data):
meandata = np.array(data['mean'])
sddata = np.array(data.sd)
ni = np.array(data.numSamples)
mean = np.average(meandata, weights=ni)
pooled_sd = np.sqrt((np.sum(np.multiply((ni - 1), np.array(sddata)**2)))/(np.sum(ni) - 1))
return mean, pooled_sd
mean,sd = df.apply(computeBias)
這是樣本數據:
id type mean sd numSamples
------------------------------------------------------------------------
1 33 -0.43 0.40 101
2 23 -0.76 0.1 100
3 33 0.89 0.56 101
4 45 1.4 0.9 100
這是完整的錯誤追溯:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-134-f4dc392140dd> in <module>()
----> 1 mean,sd = df.apply(computeBias)
C:\Users\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\series.pyc in apply(self, func, convert_dtype, args, **kwds)
2353 else:
2354 values = self.asobject
-> 2355 mapped = lib.map_infer(values, f, convert=convert_dtype)
2356
2357 if len(mapped) and isinstance(mapped[0], Series):
pandas\_libs\src\inference.pyx in pandas._libs.lib.map_infer (pandas\_libs\lib.c:66440)()
<ipython-input-133-2af38e3e29f0> in computeBias(data)
1 def computeBias(data):
2
----> 3 meandata = np.array(data['mean'])
4 sddata = np.array(data.sd)
5 ni = np.array(data.numSamples)
TypeError: 'float' object has no attribute '__getitem__'
有誰知道任何解決方法? TIA!
請在完整的錯誤追溯中編輯 –
@OferSadan:完成。 – Gingerbread
你谷歌的錯誤?有相當多的https://stackoverflow.com/questions/25950113/float-object-has-no-attribute-getitem-python-error問題引用該錯誤。 – gobrewers14