Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Incremental counts based on group within Pandas Dataframe

I wish to create an increased increment of the "type" grouped by the [ID], and [Date] columns.

DATA

ID  Date    type    
AA  Q1.21   hi  
AA  Q1.21   hi  
AA  Q1.21   hello   
AA  Q1.21   ok  
AA  Q1.21   ok  
AA  Q1.21   ok  
AA  Q2.21   hello   
AA  Q2.21   hello   
BB  Q1.21   hi  
BB  Q1.21   hi  

DESIRED

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ID  Date    type    NEW
AA  Q1.21   hi      hi01
AA  Q1.21   hi      hi02
AA  Q1.21   hello   hello01
AA  Q1.21   ok      ok01
AA  Q1.21   ok      ok02
AA  Q1.21   ok      ok03
AA  Q2.21   hello   hello01
AA  Q2.21   hello   hello02
BB  Q1.21   hi      hi01
BB  Q1.21   hi      hi02

  

DOING

df['NEW'] = df['type'] + df.groupby([*df]).cumcount().add(1).astype(str).str.zfill(2)

However, this is creating a one beside each type and not incrementing based on the Date and ID. I am still researching,
any suggestion is appreciated

>Solution :

I think you want to add with the type, not the ID:

df['New'] = df['type'] + df.groupby([*df]).cumcount().add(1).astype(str).str.zfill(2)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading