71

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()
1
  • This question includes this one. The other link has more responses and therefore might be also helpful for those who landed here. Commented Feb 20, 2023 at 16:04

2 Answers 2

122

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
Sign up to request clarification or add additional context in comments.

2 Comments

Would it be possible to get the same result with apply() or map()?
Take a look here
0

It can also be done with a combination of value_counts() and map as well. Basically, the idea is to find the counts of each group; then map these counts back to the groups.

df['count'] = df['group'].map(df['group'].value_counts())

# or
df['count'] = df['group'].map(df.groupby('group')['group'].count())

Also groupby.transform can be used with size() as well.

df['count'] = df.groupby('group').transform('size')

Both of these methods produce the following transformation.

result1

If you arrived here looking for a way to assign the per-group counter as a column, then use groupby.cumcount().

df['count'] = df.groupby('group').cumcount()+1

result2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.