gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:43:55 24 4
gpt4 key购买 nike

我有 df:

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

我想添加一个新列,用每个 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

我已经尝试过这一行,但它没有给出我想要的结果:

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

有人可以帮忙吗?

最佳答案

您可以在 groupby 对象上调用 rank 并传递参数 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

如果你想覆盖你可以做的列:

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

关于 python Pandas : How can I group by and assign an id to all the items in a group?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36063251/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com