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
312 views
in Technique[技术] by (71.8m points)

Python pandas: Add a column to my dataframe that counts a variable

I have a dataframe 'gt' like this:

org     group
org1      1
org2      1
org3      2
org4      3
org5      3
org6      3

and I would like to add column 'count' to gt dataframe to counts number member of the groups, expected results like this:

org     group   count
org1      1       2
org2      1       2
org3      2       1
org4      3       3
org5      3       3
org6      3       3

I know how to do it per one item of the group, but do not know how to make the count repeated for all of the group items, here is the code I have used:

gtcounts = gt.groupby('group').count()

Can anybody help?

question from:https://stackoverflow.com/questions/29791785/python-pandas-add-a-column-to-my-dataframe-that-counts-a-variable

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

1 Reply

0 votes
by (71.8m points)

Call transform this will return a Series aligned with the original df:

In [223]:

df['count'] = df.groupby('group')['group'].transform('count')
df
Out[223]:
    org  group  count
0  org1      1      2
1  org2      1      2
2  org3      2      1
3  org4      3      3
4  org5      3      3
5  org6      3      3

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

...