我试图将数据框传递给函数,并从数据框的不同列计算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