在pandas groupby之后为组中的每个唯一值分配唯一ID [英] assign unique ID to each unique value in group after pandas groupby

查看:177
本文介绍了在pandas groupby之后为组中的每个唯一值分配唯一ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在R中看到了解决方案,但在python中却没有.如果问题重复,请将我指向先前的问题/解决方案.

I see the solution in R but not in python. If the question is duplicate, please point me to the previous asked question/solution.

我有一个如下数据框.

df = pd.DataFrame({'col1': ['a','b','c','c','d','e','a','h','i','a'],'col2':['3:00','3:00','4:00','4:00','3:00','5:00','5:00','3:00','3:00','2:00']})

df
Out[83]: 
  col1  col2
0    a  3:00
1    b  3:00
2    c  4:00
3    c  4:00
4    d  3:00
5    e  5:00
6    a  5:00
7    h  3:00
8    i  3:00
9    a  2:00    

我想做的是groupby'col1'并为col2中的不同值分配一个唯一的ID,如下所示:

What I'd like to do is groupby 'col1' and assign a unique ID to different values in col2 as following:

col1  col2  ID
 a    2:00   0
 a    3:00   1
 a    5:00   2
 b    3:00   0
 c    4:00   0
 c    4:00   0
 ... 

我尝试使用pd.Categorical,但无法完全达到我想要的位置. 将不胜感激.谢谢.

I tried to use pd.Categorical but can't quite get to where I wanted to be. Would appreciate any help. Thanks.

推荐答案

我们可以使用 pd.factorize()方法:

In [170]: df['ID'] = df.groupby('col1')['col2'].transform(lambda x: pd.factorize(x)[0])

In [171]: df
Out[171]:
  col1  col2  ID
0    a  3:00   0
1    b  3:00   0
2    c  4:00   0
3    c  4:00   0
4    d  3:00   0
5    e  5:00   0
6    a  5:00   1
7    h  3:00   0
8    i  3:00   0
9    a  2:00   2

这篇关于在pandas groupby之后为组中的每个唯一值分配唯一ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆