Predictive Hacks

How to Access Groups From a Groupby in Pandas Dataframes

There is an easy method to get the groups from a groupby operation.

import pandas as pd



   A  B  C
0  1  a  a
1  1  b  b
2  2  a  c
3  2  c  d
4  3  b  e

Let’s do a groupby and save it to a variable.


At this point we can see the groups running the following:

{1: [0, 1], 2: [2, 3], 3: [4]}

The keys of this dictionary are the unique values of Column A which we applied the group by operation. The values are the indexes of the rows where every group has. If we use the indexes, we will get the corresponding group.

#lets get the group 1
   A  B  C
0  1  a  a
1  1  b  b

However, Pandas has also its own function to get the groups.

   A  B  C
0  1  a  a
1  1  b  b

What if we have more than one group variable? It’s the same as before but we have to use all variables inside a tuple. Let’s see the groups to understand this concept.



{(1, 'a'): [0], (1, 'b'): [1], (2, 'a'): [2], (2, 'c'): [3], (3, 'b'): [4]}

For example, if we want the group has the value 1 for A and the value “a” for B we should run the following:

group.get_group((1, 'a'))
   A  B  C
0  1  a  a

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore


Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.


Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s