daiyue
daiyue

Reputation: 7458

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

Upvotes: 0

Views: 5668

Answers (1)

BENY
BENY

Reputation: 323396

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

Upvotes: 2

Related Questions