Home > Mobile >  Incremental counts based on group within Pandas Dataframe
Incremental counts based on group within Pandas Dataframe

Time:09-27

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

CodePudding user response:

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)
  • Related