Counting the number of consecutive occurences of numbers in dataframe

Viewed 56

I have a dataframe with a dummy column that contains 1s and 0s and I would like to count for each row how many times the 1s or 0s have occurred, starting at 0 every time, and counting up for 1s and counting down for 0s I have an example below:

 import pandas as pd
 df = pd.DataFrame({'Dummy': [0, 0, 1, 1, 1, 0, 1, 1, 1, 1],
        'Counter': [-1, -2, 1, 2, 3, -1, 1, 2, 3, 4]})
1 Answers

Let's try:

blocks = df.Dummy.diff().ne(0).cumsum()
counters = df.groupby(blocks).cumcount() + 1
df['Counter'] = np.where(df['Dummy']==0, -1, 1) * counters

Output:

   Dummy  Counter
0      0       -1
1      0       -2
2      1        1
3      1        2
4      1        3
5      0       -1
6      1        1
7      1        2
8      1        3
9      1        4
Related