Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access a pandas groupby dataframe by grouped index?

Following this example I can create a simple dataframe and groupby

import pandas as pd

# Create a sample data frame
df = pd.DataFrame({'A': ['foo', 'foo', 'foo', 'bar', 'bar'],
                   'B': range(5), 'C': range(5)})

# group by 'A' and sum 'B'
gf = df.groupby('A').agg({'B': 'sum'})

The result is the grouped dataframe gf

    B
A   
bar 7
foo 3

I would like to access gf by the grouped indices. Something like...

gf['foo'] returns 3 
gf['bar'] returns 7

I would also like to plot by the grouped indices. Something like...

gf.plot('A', 'B') such that  x=['foo','bar'], y=[3,7]
like image 283
astromonerd Avatar asked Oct 24 '25 09:10

astromonerd


1 Answers

gf.reset_index(level=0, inplace=True)

gf[gf.A == 'bar']

returns:

     A  B
0  bar  7

Plot:

import matplotlib.pyplot as plt

plt.bar(gf.A, gf.B)
like image 119
LN_P Avatar answered Oct 26 '25 06:10

LN_P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!