本文介绍了 pandas 分组依据并分配分组ID,然后取消分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下格式的大数据集:
I have a large data set in the following format:
id, socialmedia
1, facebook
2, facebook
3, google
4, google
5, google
6, twitter
7, google
8, twitter
9, snapchat
10, twitter
11, facebook
我想在那时进行分组,并分配一个group_id列,然后取消分组(扩展)回各个记录.
I want to group by then and assign a group_id column and then ungroup (expand) back to individual records.
id, socialmedia, groupId
1, facebook, 1
2, facebook, 1
3, google, 2
4, google, 2
5, google, 2
6, twitter, 3
7, google, 2
8, twitter, 3
9, snapchat, 4
10, twitter, 3
11, facebook, 1
我尝试了以下操作,但最终以"DataFrameGroupBy"对象不支持项目分配.
I tried following but end up with 'DataFrameGroupBy' object does not support item assignment.
x['grpId'] = x.groupby('socialmedia')['socialmedia'].rank(method='dense').astype(int)
推荐答案
通过使用ngroup
df['grpId']=df.groupby(' socialmedia').ngroup().add(1)
df
Out[354]:
id socialmedia grpId
0 1 facebook 1
1 2 facebook 1
2 3 google 2
3 4 google 2
4 5 google 2
5 6 twitter 4
6 7 google 2
7 8 twitter 4
8 9 snapchat 3
9 10 twitter 4
10 11 facebook 1
或pd.factorize
和'categroy'
df['grpId']=pd.factorize(df[' socialmedia'])[0]+1
df
Out[358]:
id socialmedia grpId
0 1 facebook 1
1 2 facebook 1
2 3 google 2
3 4 google 2
4 5 google 2
5 6 twitter 3
6 7 google 2
7 8 twitter 3
8 9 snapchat 4
9 10 twitter 3
10 11 facebook 1
df['grpId']=df[' socialmedia'].astype('category').cat.codes.add(1)
df
Out[356]:
id socialmedia grpId
0 1 facebook 1
1 2 facebook 1
2 3 google 2
3 4 google 2
4 5 google 2
5 6 twitter 4
6 7 google 2
7 8 twitter 4
8 9 snapchat 3
9 10 twitter 4
10 11 facebook 1
这篇关于 pandas 分组依据并分配分组ID,然后取消分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!