Create new column in pandas dataframe based on pattern change in first column

Viewed 187

I have a dataframe as below:

df = pd.DataFrame({'Status': [0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1]})

which and I want to create a new column 'Group' based on the change in pattern of 'Status'. Basically I want output as below:

    Status  Group
0        0      1
1        0      1
2        1      2
3        1      2
4        1      2
5        0      3
6        0      3
7        0      3
8        0      3
9        1      4
10       1      4

Simple way is to iterate every row and then update the 'Group' column based on the pattern change. I wanted to know if there is any better way to do which is more native for pandas or numpy way of soling this issue.

1 Answers

Use pd.Series.cumsum

df['Group'] = df.Status.ne(df.Status.shift()).cumsum()

or

df['Group'] = df.Status.diff().ne(0).cumsum()

Both yield

    Status  Group
0   0       1
1   0       1
2   1       2
3   1       2
4   1       2
5   0       3
6   0       3
7   0       3
8   0       3
9   1       4
10  1       4
Related