2017-07-07 265 views
0

我試圖將數據框傳遞給函數,並從數據框的不同列計算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!

+0

請在完整的錯誤追溯中編輯 –

+0

@OferSadan:完成。 – Gingerbread

+0

你谷歌的錯誤?有相當多的https://stackoverflow.com/questions/25950113/float-object-has-no-attribute-getitem-python-error問題引用該錯誤。 – gobrewers14

回答

1
meandata = np.array(data['mean']) 
TypeError: 'float' object has no attribute '__getitem__' 

__getitem__是Python嘗試在您使用索引時調用的方法。在標記的行中,意思是data['mean']正在產生錯誤。很明顯,data是一個數字,一個浮動對象。你不能索引一個數字。

data['mean']看起來像是要使用命名索引從字典或數據框中獲取項目。我不會深入其他代碼來確定你的意圖。

你需要做什麼它明白什麼data真的,它產生了什麼。


您在df.apply(....)利用這一點,顯然認爲它只是意味着

computeBias(df) # or 
computeBias(df.data) 

而是我懷疑apply的迭代,在某些方面,在數據幀,並通過值或dataseries到你的代碼。它沒有傳遞整個數據幀。

+0

我想這是應用函數的一些問題。我使用apply,因爲我想傳遞分組對象以及函數。但它不管用。所以,我只是遍歷組並通過發送相應的列來計算統計信息。 – Gingerbread

相關問題