Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (50.2k points)

I am using .size() on a groupby result to count how many items are in each group.

I would like the result to be saved to a new column name without manually editing the column names array, how can it be done?

Thanks

This is what I have tried:

grpd = df.groupby(['A','B']) grpd['size'] = grpd.size() grpd

and the error I got:

TypeError: 'DataFrameGroupBy' object does not support item assignment (on the second line)

1 Answer

0 votes
by (107k points)

The built-in method size() of DataFrameGroupBy objects returns a Series object with the group sizes. If you need a DataFrame whose column is equal to the group sizes, indexed by the groups, with a custom name, you can use the .to_frame() method and use the desired column name as its argument.

grpd = df.groupby(['A','B']).size().to_frame('size')

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...