I got a DataFrame with monthly record, and I would like to calculate the difference between latest month with the one before 6 months. However, for those who didn't have completed 6 months record, can I calculate the difference with the one it has the earliest record like below.
Client Month CAV
A 2021-09 30
A 2021-08 20
A 2021-07 10
A 2021-06 5
A 2021-05 10
A 2021-04 5
A 2021-03 10
B 2021-08 50
B 2021-07 10
B 2021-06 30
I used df['CAV_diff'] = df.groupby('Client')['CAV'].diff(-5), it will get:
Client Month CAV CAV_diff
A 2021-09 30 25 (=30-5)
A 2021-08 20 10 (=20-10)
A 2021-07 10 N/A
A 2021-06 5 N/A
A 2021-05 10 N/A
A 2021-04 5 N/A
A 2021-03 10 N/A
B 2021-08 50 N/A
B 2021-07 10 N/A
B 2021-06 30 N/A
Can I get the result as below:
Client Month CAV CAV_diff
A 2021-09 30 25 (=30-5)
A 2021-08 20 10 (=20-10)
A 2021-07 10 0 (=10-10)
A 2021-06 5 -5 (=5-10)
A 2021-05 10 0
A 2021-04 5 -5
A 2021-03 10 0
B 2021-08 50 20
B 2021-07 10 -20
B 2021-06 30 0