Python Forum
Create a sequential number (counter) and reset at each duplicate
Thread Rating:
  • 1 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Create a sequential number (counter) and reset at each duplicate
#1
Hi,
I want to assign serial number but reset at repeating row
I use the below code, but I am not achieving the desired output.

import pandas as pd

df = pd.DataFrame({'ID':['A1','A2','A1','A3','A4','A3','A4','A5'],\
'sub_set':['A.0','A.0','A.0','A.0','A.0','A.0','A.0','A.0'],\
'grp':['A','A','A','A','A','A','A','A'],\
'rank':[1,2,1,1,2,3,9,6]})
df['C'] = df.groupby(['sub_set']).cumcount()+1
I am getting below output:

ID grp  rank sub_set  C
A1   A     1     A.0  1
A2   A     2     A.0  2
A1   A     1     A.0  3
A3   A     1     A.0  4
A4   A     2     A.0  5
A3   A     3     A.0  6
A4   A     9     A.0  7
A5   A     6     A.0  8
But desired output:

ID grp  rank sub_set  C
A1   A     1     A.0  1
A2   A     2     A.0  2
A1   A     1     A.0  1
A3   A     1     A.0  2
A4   A     2     A.0  3
A3   A     3     A.0  1
A4   A     9     A.0  2
A5   A     6     A.0  3
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Give visit number ( or counter) within the same time frame balthordu 1 247 Jun-27-2022, 09:51 AM
Last Post: Larz60+
  Create Dict from multiple Lists with duplicate Keys rhat398 10 2,474 Jun-26-2021, 11:12 AM
Last Post: Larz60+
  Four sequential bytes; Need to remove high order bit in each to get correct output GrandSean 5 1,786 Feb-06-2021, 07:17 PM
Last Post: GrandSean
  Finding sequential invoice william888 0 978 Mar-24-2020, 12:41 AM
Last Post: william888
  Sequential color background swisha 2 1,414 Mar-05-2020, 03:43 PM
Last Post: Larz60+
  Reset counter when the day turns over Rehan11 3 4,389 Jan-03-2019, 05:02 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020