Python Pandas:如何分组并为组中的所有项目分配一个 id?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36063251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:53:27  来源:igfitidea点击:

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

pythonpandasindexinggroup-by

提问by UserYmY

I have df:

我有 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:

我想添加一个新列,用每个 orgid 的数字 ID 替换域列:

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?

有人可以帮忙吗?

回答by EdChum

You can call rankon the groupbyobject and pass param method='first':

你可以调用rankgroupby对象,并通过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')

回答by Shahnawaz Akhtar

You can use LabelEncoder from sklearn.preprocessing like :

您可以使用 sklearn.preprocessing 中的 LabelEncoder ,例如:

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