Q:

Iterating over a column in Pandas DataFrame with groupby conditions

I have a dataset in a pandas DataFrame. Data are sorted by ["Customer_Id","Campaign"].
My goal though is to add another step to the groupby function. For each campaign there is batches, new batches is represented by the New_rank == 1.  

I would like to add a column = "Occurence" that gives me an numbered "batch" for per Customer_Id & campaign.
Desired output like this in this case:

Any ideas would be greatly appreciated!

A:

Use cumsum:
df['Occurence'] = df.groupby(['CustomerId','Campaign'])['New_rank'].cumsum()

Output:
    CustomerId  Campaign  New_rank  Occurence
0            1         1         1          1
1            1         1         0          1
2            1         1         1          2
3            1         2         1          1
4            1         2         1          2
5            2         1         1          1
6            2         1         0          1
7            2         1         0          1
8            2         2         1          1
9            2         3         1          1
10           2         3         0          1

