1

I have a Series that look like this

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

and I would like to generate a second counter that looks like this

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

How can I do that in python?

1 Answer 1

3

If 1 is always start of groups then create mask by compare by Series.eq and then add Series.cumsum for cumulative sum:

df['col2'] = df['col'].eq(1).cumsum()
print (df)
    col  col2
0     1     1
1     2     1
2     3     1
3     4     1
4     1     2
5     2     2
6     3     2
7     1     3
8     2     3
9     3     3
10    1     4
11    2     4
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.