How to access a certain row in Pandas DataFrame after a group by and aggregate operation

Viewed 2988

I want to access a row in a Pandas DataFrame after a group by and an aggregate operation.

import pandas as pd
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
                           'foo', 'bar'],
                    'B' : [1, 2, 3, 4, 5, 6],
                    'C' : [2.0, 5., 8., 1., 2., 9.]})

grouped = df.groupby('A').agg({"C":{"size","mean"}})

grouped

Now I want to the access the row where value of A is "foo". When i tried to use grouped[grouped["A"]=="foo"], I got an error saying KeyError: 'A'

Specifically, I want the size for "foo".

When I searched online, I saw a few posts related to multiIndex. But I couldn't get it to work.

This might seem like a trivial question. I am new to Pandas and finding it a bit difficult to understand.

1 Answers

You should use loc:

grouped.loc['foo']
Out[1]: 
C  size    3.0
   mean    4.0
Name: foo, dtype: float64
Related