2 回答
TA贡献1844条经验 获得超8个赞
您可以通过 A 和 B 计算 C 的聚合总和,然后将结果数据帧与原始数据帧合并
>> df
A B C D
0 foo one 1 15
1 bar one 2 10
2 foo two 4 20
3 bar three 4 5
4 foo two 5 6
5 bar two 6 9
6 foo one 7 8
7 foo three 8 15
df2 = df.groupby(['A','B']).sum().drop(['D'], axis=1).rename(columns={'C':'E'})
>> df2
E
A B
bar one 2
three 4
two 6
foo one 8
three 8
two 9
合并df和df2可以得到结果:
>> df.merge(df2.reset_index(), on=['A', 'B'], how='left')
A B C D E
0 foo one 1 15 8
1 bar one 2 10 2
2 foo two 4 20 9
3 bar three 4 5 4
4 foo two 5 6 9
5 bar two 6 9 6
6 foo one 7 8 8
7 foo three 8 15 8
添加回答
举报