I have a pandas dataframe with the following format
name | is_valid | account | transaction
Adam | True | debit | +10
Adam | False | credit | +10
Adam | True | credit | +10
Benj | True | credit | +10
Benj | False | debit | +10
Adam | True | credit | +10
I want to create two new columns credit_cumulative and debit_cumulative.
For credit_cumulative, it counts the cumulative sum of the transaction column for the corresponding person, and for the corresponding account in that row, the transaction column will count only if is_valid column is true.
debit_cumulative wants to behave in the same way.
In the above example, the result should be:
from | is_valid | account | transaction | credit_cumulative | debit_cumulative
Adam | True | debit | +10 | 0 | 10
Adam | False | credit | +10 | 0 | 10
Adam | True | credit | +10 | 10 | 10
Benj | True | credit | +10 | 10 | 0
Benj | False | debit | +10 | 10 | 0
Adam | True | credit | +10 | 20 | 10
To illustrate, the first row is Adam, and account is debit, is_valid is true, so we increase debit_cumulative by 10.
For the second row, is_valid is negative. So transaction does not count. Name is Adam, is credit_cumulative and debit_cumulative will remain the same.
All rows shall behave this way.
Here is the code to the original data I described:
d = {'name': ['Adam', 'Adam', 'Adam', 'Benj', 'Benj', 'Adam'], 'is_valid': [True, False, True, True, False, True], 'account': ['debit', 'credit', 'credit', 'credit', 'debit', 'credit'], 'transaction': [10, 10, 10, 10, 10, 10]}
df = pd.DataFrame(data=d)