Philippe Haumesser
Philippe Haumesser

Reputation: 647

difference between rows with pandas data frame

this is my dataframe sample.

enter image description here

I want to add a column which give difference between previous period by GL. My result should be:

enter image description here

thanks

Upvotes: 0

Views: 30

Answers (1)

Georgina Skibinski
Georgina Skibinski

Reputation: 13387

Try:

df["diff"]=df.groupby("GL")["value"].diff().fillna(df["value"])

Outputs for the sample data:

import pandas as pd

df=pd.DataFrame({"a": list("xyzyyzvx"), "b": [4.6, 33.2, -5, 2.34,1,9,-6.89,23]})

df["diff"]=df.groupby("a")["b"].diff().fillna(df["b"])

>>> df

   a      b   diff
0  x   4.60   4.60
1  y  33.20  33.20
2  z  -5.00  -5.00
3  y   2.34 -30.86
4  y   1.00  -1.34
5  z   9.00  14.00
6  v  -6.89  -6.89
7  x  23.00  18.40

Upvotes: 1

Related Questions