【发布时间】:2021-09-22 21:06:18
【问题描述】:
我在 pandas python 中做一些任务。
我有这样的数据:
col1 |col2 |col3 |col4 |col5 | col6
delhi |assam |"f" |78.3 |87.1 | B2C
delhi |goa |"f" |78.3 |87.1 | B2C
delhi |goa |"f" |78.3 |87.1 | B2C
delhi |assam |"f" |78.3 |87.1 | B2C
up |assam |"f" |78.3 |87.1 | B2B
delhi |assam |"f" |78.3 |87.1 | B2B
现在我想过滤 col6 为 B2C 的那些行。 过滤后,我想对 col1 和 col2 进行分组并对 col4 和 col5 求和。
所以输出应该是这样的:
col1 |col2 |col3 |col4 |col5 | col6
delhi |assam |"f" |156.6|174.2| B2C
delhi |goa |"f" |156.6|174.2| B2C
up |assam |"f" |78.3 |87.1 | B2B
delhi |assam |"f" |78.3 |87.1 | B2B
我尝试过的方法:
df.loc[df['col6'] == 'B2C'].groupby(['col1', 'col2']).agg({'col4':'sum', 'col5':'sum'})
但我不知道如何将此结果附加到原始数据框。如果我能做得比这更好,也请指导我。
【问题讨论】:
标签: python pandas pandas-groupby aggregate