简体   繁体   中英

pandas sum the differences between two columns in each group

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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