Generate column of unique ID in pandas

前端 未结 1 923
滥情空心
滥情空心 2021-01-23 14:08

I have a dataframe with three columns, bins_x, bins_y and z. I wish to add a new column unique that is an \"index\" of sorts

相关标签:
1条回答
  • 2021-01-23 14:39

    Use groupby and cumcount:

    df['unique'] = df.groupby(['bins_x','bins_y']).cumcount()
    
    >>> df.sort_values(['bins_x', 'bins_y']).head(10)
         bins_x  bins_y    z  unique
    207       1       1    4       0
    259       1       1  313       1
    327       1       1  300       2
    341       1       1   64       3
    440       1       1  398       4
    573       1       1   96       5
    174       1       2  219       0
    563       1       2  398       1
    796       1       2  417       2
    809       1       2  167       3
    
    0 讨论(0)
提交回复
热议问题