Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

581
Views
Pandas group by cumsum with a flag condition

Assuming i have the following data frame

date flag user num
0 2019-01-01 1 a 10
1 2019-01-02 0 a 20
2 2019-01-03 1 b 30
3 2019-03-04 1 b 40

I want to create a cumulative sum of the nums grouped by user only if flag == 1 so i will get this:

date flag user num cumsum
0 2019-01-01 1 a 10 10
1 2019-01-02 0 a 20 10
2 2019-01-03 1 b 30 30
3 2019-03-04 1 b 40 70

So far i was able to cumsum by flag, disregarding the group by user

df['cumsum'] = df[df['flag'] == 1 ]['num'].transform(pd.Series.cumsum)

or cumsum by user disregarding the flag

df['cumsum'] = df.groupby('user')['num'].transform(pd.Series.cumsum)

I need help making them work together.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You could multiply num by flag to make num = 0 where flag = 0, group by user, and cumsum:

df['cumsum'] = df['num'].mul(df['flag']).groupby(df['user']).cumsum()

Output:

>>> df
         date  flag user  num  cumsum
0  2019-01-01     1    a   10      10
1  2019-01-02     0    a   20      10
2  2019-01-03     1    b   30      30
3  2019-03-04     1    b   40      70
over 4 years ago · Santiago Trujillo Report

0

With series.where to mark num==0 where flag is 0 then groupby+cumsum:

df['cumsum'] =  df['num'].where(df['flag'].eq(1),0).groupby(df["user"]).cumsum()

         date  flag user  num  cumsum
0  2019-01-01     1    a   10      10
1  2019-01-02     0    a   20      10
2  2019-01-03     1    b   30      30
3  2019-03-04     1    b   40      70
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!