首页 > 解决方案 > Pandas groupby 并执行算术运算

问题描述

我有一个熊猫数据框,我想按 3 列分组并执行算术运算来计算每组的新列。这是我到目前为止所尝试的:

df['c'] = df.groupby(['date', 'year', 'month']).apply(lambda x: sum(x['a']*x['weight'])/sum(x['b']*x['weight']))

但它抛出了这个错误:

ValueError: Buffer dtype mismatch, expected 'Python object' but got 'long' 在处理上述异常期间,发生另一个异常:TypeError: incompatible index of inserted column with frame index

我还尝试了 np.sum() 函数:

df['c'] = df.groupby(['date', 'year', 'month']).apply(lambda x: np.sum(x['a']*x['weight'])/np.sum(x['b']*x['weight']))

但它也会引发同样的错误。

我不确定这是否与数据或我的代码有关。

任何帮助表示赞赏!谢谢!

标签: pythonpandaspandas-groupby

解决方案


我认为您需要自定义功能:

df = pd.DataFrame({
        'date':['2010-01-01'] * 6,
         'year':[2004,2005,2004,2005,2005,2004],
         'month':[7] * 6,
         'a':[1,3,5,7,1,0],
         'b':[3,5,7,1,0,8],
         'weight':[5,3,6,9,2,4],
         'col':list('aaabbb')
})

def f(x):
    x['c'] = (x['a']*x['weight']).sum() /(x['b']*x['weight']).sum()
    return x

df = df.groupby(['date', 'year', 'month']).apply(f)
print (df)
         date  year  month  a  b  weight col         c
0  2010-01-01  2004      7  1  3       5   a  0.393258
1  2010-01-01  2005      7  3  5       3   a  3.083333
2  2010-01-01  2004      7  5  7       6   a  0.393258
3  2010-01-01  2005      7  7  1       9   b  3.083333
4  2010-01-01  2005      7  1  0       2   b  3.083333
5  2010-01-01  2004      7  0  8       4   b  0.393258

推荐阅读