python - 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']))
但它也会引发同样的错误。
我不确定这是否与数据或我的代码有关。
任何帮助表示赞赏!谢谢!
解决方案
我认为您需要自定义功能:
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
推荐阅读
- qt-installer - Qt 安装程序框架 - 检查目标目录,如果存在则运行卸载程序
- matlab - 如何在 MATLAB 中将数组保存/导出为 PDF
- ballerina - 我如何在芭蕾舞演员中进行类型检查
- typescript - require('react-native').NativeModules.RNRandomBytes 为空
- linux - httpd 未按预期读取 conf/httpd.conf 中的文档根目录
- ios - 如何从表中获取字距对的值?
- sql - 如何计算明细表中的唯一组合?
- mysql - 用一些逻辑不工作的mysql创建事件
- ansible - 在 v2.5 的剧本中为主机使用变量
- windows - 随机批量停止服务无济于事