Pandas groupby cumulative count

后端 未结 1 1512
眼角桃花
眼角桃花 2020-12-21 17:34

How do I do a cumcount on two groupings, id and name? For example I have:

id  name
1   name1
1   name1
1   name2
2   name3
2   name3
2   name3
相关标签:
1条回答
  • 2020-12-21 18:14

    You can use groupby.cumcount:

    df['cumcount'] = df.groupby(['id', 'name']).cumcount() + 1
    
    df
    #  id   name    cumcount
    #0  1   name1   1
    #1  1   name1   2
    #2  1   name2   1
    #3  2   name3   1
    #4  2   name3   2
    #5  2   name3   3
    
    0 讨论(0)
提交回复
热议问题