Search code examples
pandascumsum

Integer Counter when value in next row changes


I'm having a problem adding a "counter column" in my dataframe.

I parsed values from multiple columns into so called "merged_attributes" and now I want to create a counter that increments by 1 when value of "merged attributes" columns changes.

I have below dataframe, last column is desired column:

   Price  UNIQUE  MERGED_ATRIBUTE  COUNTER
0  52.08       1           52.081        1
1  52.08       1           52.081        1
2  52.20       1           52.210        2
3  52.20       1           52.210        2
4  52.20       1           52.210        2
5  52.20       1           52.210        2
6  52.20       1           52.210        2
7  52.20       1           52.210        2
8  70.10       1           70.110        3

How do I achieve this?

thanks a lot!


Solution

  • Or with cumsum() and equality check with previous row:

    c = df['MERGED_ATRIBUTE']
    df['COUNTER'] = c.ne(c.shift()).cumsum()
    

       Price  UNIQUE  MERGED_ATRIBUTE  COUNTER
    0  52.08       1           52.081        1
    1  52.08       1           52.081        1
    2  52.20       1           52.210        2
    3  52.20       1           52.210        2
    4  52.20       1           52.210        2
    5  52.20       1           52.210        2
    6  52.20       1           52.210        2
    7  52.20       1           52.210        2
    8  70.10       1           70.110        3