How to assign a name to the size() column?

pandas, python

Solution

The result of `df.groupby(...)` is not a DataFrame. To get a DataFrame back, you have to apply a function to each group, transform each element of a group, or filter the groups.

It seems like you want a DataFrame that contains (1) all your original data in `df` and (2) the count of how much data is in each group. These things have different lengths, so if they need to go into the same DataFrame, you'll need to list the size redundantly, i.e., for each row in each group.

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

(Aside: It's helpful if you can show succinct sample input and expected results.)

Problem

I am using `.size()` on a groupby result in order 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? 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)

Original source

Related problems