user3447653
user3447653

Reputation: 4148

Grouping based on one column in pandas dataframe

I am trying to group by based on Group in the below dataframe.

             Group
               G1
               G1
               G1
               G2
               G2

After Group by in the above dataframe,

             Group            Count
               G1                  3
               G1                  2

Then, I need to do a pivot table of the above dataframe based on Group.

                                  Count
          Group
           G1                     3
           G2                     2

Upvotes: 2

Views: 3317

Answers (3)

Khris
Khris

Reputation: 3212

The column you groupby your dataframe becomes the index of the grouped dataframe, you need a second column to do this. You can just create one like this:

df = df.reset_index()

Just be careful, the new column is called index, it should be renamed.

With the new column this works just fine:

df.groupby('Group').count()

Or if you don't want Group to be the index of the new dataframe:

df.groupby('Group',as_index=False).count()

You can't use as_index=False with a one-column dataframe by the way.

Upvotes: 0

danielhadar
danielhadar

Reputation: 2161

Use: df.groupby('Group').size()

Example:

In[53]: df = pd.DataFrame({'Group': ['G1', 'G1', 'G1', 'G2', 'G2']})
In[54]: df
Out[54]: 
  Group
0    G1
1    G1
2    G1
3    G2
4    G2

In[55]: df.groupby('Group').size()
Out[55]: 
Group
G1    3
G2    2

Upvotes: 2

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210812

depending on what you want to achieve:

In [27]: df.groupby('Group').size().rename('Count').reset_index()
Out[27]:
  Group  Count
0    G1      3
1    G2      2

In [28]: df.groupby('Group').size().rename('Count').to_frame()
Out[28]:
       Count
Group
G1         3
G2         2

Upvotes: 2

Related Questions