Rohit Lamba
Rohit Lamba

Reputation: 186

Execute Pandas Groupby and populate difference of first value and last value in all rows

I have a dataframe like below:

GRP_ID   Value
9273346  51
9273346  74
9273346  40
9273346  22
9273347  405
9273347  405
9273347  405
9273347  405
9273347  405
9273347  405
9273347  405
9273348  26
9273348  84
9273348  74
9273348  25
9273348  49
9273350  4522

I want to populate the difference of (last value and first value) for every group_id in all rows. I need the result as below:

ID       Value  Result
9273346  51     -29
9273346  74     -29
9273346  40     -29
9273346  22     -29
9273347  405    0
9273347  405    0
9273347  405    0
9273347  405    0
9273347  405    0
9273347  405    0
9273347  405    0
9273348  26     23
9273348  84     23
9273348  74     23
9273348  25     23
9273348  49     23
9273350  4522   0

Upvotes: 0

Views: 34

Answers (1)

moys
moys

Reputation: 8033

df['Result']=df.groupby('GRP_ID')['Value'].transform(lambda x: (x.values[0]-x.values[-1]))

Output

     GRP_ID     Value   Result
0   9273346     51      29
1   9273346     74      29
2   9273346     40      29
3   9273346     22      29
4   9273347     405     0
5   9273347     405     0
6   9273347     405     0
7   9273347     405     0
8   9273347     405     0
9   9273347     405     0
10  9273347     405     0
11  9273348     26      -23
12  9273348     84      -23
13  9273348     74      -23
14  9273348     25      -23
15  9273348     49      -23
16  9273350     4522    0

Upvotes: 2

Related Questions