Gev_2000
Gev_2000

Reputation: 59

splitting/grouping pandas dataframe column

I have a dataframe with a column populated with groups of 1s and 0s. How can I assign each group a consecutive number beginning from 1?

I have tried a for loop across rows, but I need a column operation for fast performance.

d = {'col1': [1,1,1,0,0,1,1,0,0,0,1,1]}
df1 = pd.DataFrame(data=d)
df1

col1 0 1 1 1 2 1 3 0 4 0 5 1 6 1 7 0 8 0 9 0 10 1 11 1

I need the following output:

col1 col2 0 1 1 1 1 1 2 1 1 3 0 2 4 0 2 5 1 3 6 1 3 7 0 4 8 0 4 9 0 4 10 1 5 11 1 5

Upvotes: 2

Views: 51

Answers (1)

jezrael
jezrael

Reputation: 862601

You can compare shifted values for not equal and add cumulative sum by Series.cumsum:

df1['col2'] = df1['col1'].ne(df1['col1'].shift()).cumsum()
print (df1)
    col1  col2
0      1     1
1      1     1
2      1     1
3      0     2
4      0     2
5      1     3
6      1     3
7      0     4
8      0     4
9      0     4
10     1     5
11     1     5

Upvotes: 3

Related Questions