pandas sum the differences between two columns in each group

試著忘記壹切 提交于 2021-02-08 10:45:26

问题


I have a df looks like,

A               B              C    D
2017-10-01      2017-10-11     M    2017-10
2017-10-02      2017-10-03     M    2017-10
2017-11-01      2017-11-04     B    2017-11
2017-11-08      2017-11-09     B    2017-11
2018-01-01      2018-01-03     A    2018-01

the dtype of A and B are datetime64, C and D are of strings;

I like to groupby C and D and get the differences between B and A,

df.groupby(['C', 'D']).apply(lambda row: row['B'] - row['A'])

but I don't know how to sum such differences in each group and assign the values to a new column say E, possibly in a new df,

C    D          E
M    2017-10    11
M    2017-10    11
B    2017-11    4
B    2017-11    4
A    2018-01    2

回答1:


Base on you code

df.merge(df.groupby(['C', 'D']).apply(lambda row: row['B'] - row['A']).sum(level=[0,1]).reset_index())
Out[292]: 
           A          B  C        D       0
0 2017-10-01 2017-10-11  M  2017-10 11 days
1 2017-10-02 2017-10-03  M  2017-10 11 days
2 2017-11-01 2017-11-04  B  2017-11  4 days
3 2017-11-08 2017-11-09  B  2017-11  4 days
4 2018-01-01 2018-01-03  A  2018-01  2 days


来源:https://stackoverflow.com/questions/49324988/pandas-sum-the-differences-between-two-columns-in-each-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!