在 pandas 中生成唯一ID的列 [英] Generate column of unique ID in pandas

查看:92
本文介绍了在 pandas 中生成唯一ID的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含三列的数据框,分别为bins_xbins_yz.我希望添加一个新列unique,该列是bins_xbins_y的唯一组合的某种索引".以下是我要附加的示例.

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 for that unique combination of bins_x and bins_y. Below is an example of what I would like to append.

请注意,为清晰起见,我对数据框进行了排序,但是在此情况下排序并不重要.

Note that I ordered the dataframe for clarity, but order does not matter in this context.

import numpy as np
import pandas as pd
np.random.seed(12)
n = 1000
height = 20
width = 20
bins_x = np.random.randint(1, width, size=n)
bins_y = np.random.randint(1, height, size=n)
z = np.random.randint(1, 500, size=n)

df = pd.DataFrame({'bins_x': bins_x, 'bins_y': bins_y, 'z': z})
print(df.sort_values(['bins_x', 'bins_y'])



     bins_x  bins_y    z   unique
23        0       0  462   0
531       0       0  199   1
665       0       0  176   2
363       0       1  219   0
468       0       1  450   1
593       0       1  385   2
609       0       1   74   3
663       0       1   46   4
14        0       2  242   0
208       0       2  381   1
600       0       2  445   2
865       0       2  221   3
400       0       3  178   0
75        0       4  281   0
140       0       4  205   1
282       0       4   47   2
838       0       4  212   3

推荐答案

使用groupbycumcount:

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

这篇关于在 pandas 中生成唯一ID的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆