Incremental counts based on group within Pandas Dataframe

Question:

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

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

Asked By: Lynn

||

Answers:

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)
Answered By: Quang Hoang
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.