Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

python - pandas group by and assign a group id then ungroup

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

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

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

By using 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

Or pd.factorize and '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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...