How to make column counter that will show when the value in other column change

I have a column "status" in dataframe that has following values:

increase
increase
increase
increase
decline
decline
decline
increase
increase
decline

I need to make counter that will change each time the value in column 'status' change from decline to increase. It should look like this:

"status"          "counter"
increase          1
increase          1
increase          1
increase          1
decline           2
decline           2
decline           2
increase          3
increase          3
decline           4

What is appropriate way to do it in python?

Upvotes: 1

Views: 46

Answers (1)

Umar.H
Umar.H

Reputation: 23099

you can create a boolean then just apply a cumulative sum.

df['counter'] = df['status'].ne(df['status'].shift()).cumsum() 

  status  counter
0  increase        1
1  increase        1
2  increase        1
3  increase        1
4   decline        2
5   decline        2
6   decline        2
7  increase        3
8  increase        3
9   decline        4

Upvotes: 2

Related Questions