3

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]
astromonerd
  • 857
  • 1
  • 14
  • 30

2 Answers2

5
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)
LN_P
  • 1,268
  • 2
  • 18
  • 33
0

What about:

import matplotlib.pyplot as plt

for k in gf['B'].index:
    print "{}: {}".format(k, gf['B'].loc[k])

plt.bar(gf['B'].index, map(lambda i: gf['B'].loc[i], gf['B'].index))
plt.show()
sjplural
  • 543
  • 1
  • 5
  • 11