想要分配ID到重复的行

时间:2019-04-12 13:55:38

标签: python-3.x pandas

id    name     age      year

0     khu       12      2018

1     she       21      2019

2     waqar     22      2015

3     khu       12      2018

4     she       21      2018

5     waqar     22      2015

想要这样

id    name     age      year

0     khu       12      2018

1     she       21      2019

2     waqar     22      2015

0     khu       12      2018

1     she       21      2018

2     waqar     22      2015

2 个答案:

答案 0 :(得分:5)

使用GroupBy.ngroup

df['id'] = df.groupby('name', sort=False).ngroup()
#if need grouping by multiple columns for check duplicates
#df['id'] = df.groupby(['name','age'], sort=False).ngroup()
print (df)
   id   name  age  year
0   0    khu   12  2018
1   1    she   21  2019
2   2  waqar   22  2015
3   0    khu   12  2018
4   1    she   21  2018
5   2  waqar   22  2015

答案 1 :(得分:3)

也可以使用factorizecategorycat.codessklearn LabelEncoder

进行检查
df['id']=pd.factorize(df['name'])[0]
df
Out[470]: 
   id   name  age  year
0   0    khu   12  2018
1   1    she   21  2019
2   2  waqar   22  2015
3   0    khu   12  2018
4   1    she   21  2018
5   2  waqar   22  2015