how to increment a value every time a certain condition is met in pandas dataframe

  pandas, python

I have a df that looks like this:

time  val
0      1
1      1
2      2
3      3
4      1
5      2

How do I create new columns that hold the cumulative sum of occurance of a condition? In this case, I want to create a column for each unique value in val that holds the cumulative sum at the given row of occurences. See below:

time  val  sum_1   sum_2    sum_3
0      1    1        0       0 
1      1    2        0       0
2      2    2        1       0
3      3    2        1       1
4      1    3        1       1
5      2    3        2       1

Source: Python Questions

LEAVE A COMMENT