Nandini
Nandini

Reputation: 35

pandas DataFrame: Calculate Sum based on boolean values in another column

I am fairly new to Python and I trying to simulate the following logic with in pandas

enter image description here

I am currently looping throw the rows and want to sum the values in the AMOUNT column in the prior rows but only till the last seen 'TRUE' value. It seems inefficient with the actual data (I have a dataframe of about 5 million rows)? Was wondering what the efficient way of handling such a logic in Python would entail?

Logic: The logic is that if FLAG is TRUE I want to sum the values in the AMOUNT column in the prior rows but only till the last seen 'TRUE' value. Basically sum the values in 'AMOUNT' between the rows where FLAG is TRUE

Upvotes: 2

Views: 1039

Answers (2)

Ark Lomas
Ark Lomas

Reputation: 201

maybe try something around the following:

import pandas

df = pd.read_csv('name of file.csv')

df['AMOUNT'].sum()

Upvotes: 2

BENY
BENY

Reputation: 323346

Check with cumsum and transform sum

df['SUM']=df.groupby(df['FLAG'].cumsum()).Amount.transform('sum').where(df.FLAG)

Upvotes: 4

Related Questions