Running subtraction calculation

Question:

I have this dataframe and I want to achieve this type of running subtraction calculation:

enter image description here

For ID 1 at index 1, the payment of 10 must be subtracted from the amount of 1000 and result of 990 placed in balance field.
For ID 1 at index 2, the payment of 15 must be subtracted from the 990 and result placed in balance which in this case was 975.
For ID 1 at index 3, the payment of 20 must be subtracted from the 975 and result placed in balance which in this case was 955.

For ID 2 at index 1, the payment of 5 must be subtracted from the amount of 200 and result of 195 placed in balance field.
For ID 2 at index 2, the payment of 5 must be subtracted from the 195 and result of 190 placed in balance field.

Asked By: JasonX

||

Answers:

df['bal']=df['amount']-df.groupby('ID')['payment'].transform('cumsum')
df
    ID  payment     amount  balance     bal
0   1        10       1000      990     990
1   1        15       1000      975     975
2   1        20       1000      955     955
3   2         5        200      195     195
4   2         5        200      190     190
Answered By: Naveed
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.