繁体   English   中英

Pandas groupby 并执行算术运算

[英]Pandas groupby and perform arithmetic operations

我有一个 pandas dataframe 我想按 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() function:

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

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

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

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

我认为您需要自定义 function:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM