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
Python Pandas: How can I group by and assign an id to all the items in a group?
提问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 rank
on the groupby
object and pass param method='first'
:
你可以调用rank
的groupby
对象,并通过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)