increment a value each time the next row is different from the previous one

Viewed 310

I have this df :

name
str_a
str_a
str_a
str_b
str_b
str_c
str_c

In the column name I got different str, I want to create another column named number which has for the first row 0 then each time the previuous name is different from the next one, it adds +1 to the previous number. The expected result would be :

name  number
str_a 0
str_a 0
str_a 0
str_b 1
str_b 1 
str_c 2 
str_c 2

Is there a way to do that without a loop ?

Thanks !

1 Answers

Let us try shift with cumsum , notice you may can check df['name'].factorize()[0] , however, if the name repeat but not always continue in a row factorize will not work

df['name'].ne(df['name'].shift()).cumsum()-1
Out[10]: 
0    0
1    0
2    0
3    1
4    1
5    2
6    2
Name: name, dtype: int32
Related