Python Pandas: How can I group by and assign an id to all the items in a group?

允我心安 提交于 2020-01-03 13:56:07

问题


I have df:

domain           orgid
csyunshu.com    108299
dshu.com        108299
bbbdshu.com     108299
cwakwakmrg.com  121303
ckonkatsunet.com    121303

I would like to add a new column with replaces domain column with numeric ids per orgid:

domain           orgid   domainid
csyunshu.com    108299      1
dshu.com        108299      2
bbbdshu.com     108299      3
cwakwakmrg.com  121303      1
ckonkatsunet.com 121303     2

I have already tried this line but it does not give the result I want:

df.groupby('orgid').count['domain'].reset_index()

Can anybody help?


回答1:


You can call rank on the groupby object and pass param method='first':

In [61]:
df['domainId'] = df.groupby('orgid')['orgid'].rank(method='first')
df

Out[61]:
             domain   orgid  domainId
0      csyunshu.com  108299         1
1          dshu.com  108299         2
2       bbbdshu.com  108299         3
3    cwakwakmrg.com  121303         1
4  ckonkatsunet.com  121303         2

If you want to overwrite the column you can do:

df['domain'] = df.groupby('orgid')['orgid'].rank(method='first')



回答2:


You can use LabelEncoder from sklearn.preprocessing like :

df["domain"] = LabelEncoder().fit_transform(df.domain)


来源:https://stackoverflow.com/questions/36063251/python-pandas-how-can-i-group-by-and-assign-an-id-to-all-the-items-in-a-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!