jimmy15923
jimmy15923

Reputation: 291

Python value difference in dataframe by group key

I have a DataFrame

name   value
A       2
A       4
A       5
A       7
A       8
B       3
B       4
B       8
C       1
C       3
C       5 

And I want to get the value differences based on each name like this

name   value   dif
A       2      0
A       4      2
A       5      1
A       7      2
A       8      1
B       3      0
B       4      1
B       8      4
C       1      0
C       3      2
C       5      2

Can anyone show me the easiest way?

Upvotes: 6

Views: 1797

Answers (1)

Nickil Maveli
Nickil Maveli

Reputation: 29711

You can use GroupBy.diff to compute the difference between consecutive rows per grouped object. Optionally, filling missing values( first row in every group) by 0 and casting them finally as integers.

df['dif'] = df.groupby('name')['value'].diff().fillna(0).astype(int)
df

enter image description here

Upvotes: 6

Related Questions