如何按分组索引访问pandas groupby数据框?

时间:2018-07-01 14:43:32

标签: python python-3.x pandas pandas-groupby

this example之后,我可以创建一个简单的数据框和分组依据

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'})

结果是分组的数据帧gf

    B
A   
bar 7
foo 3

我想通过分组索引访问gf。像...

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

我也想按分组索引进行绘制。像...

gf.plot('A', 'B') such that  x=['foo','bar'], y=[3,7]

2 个答案:

答案 0 :(得分:1)

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

gf[gf.A == 'bar']

返回:

     A  B
0  bar  7

情节:

import matplotlib.pyplot as plt

plt.bar(gf.A, gf.B)

答案 1 :(得分:0)

那又怎么样:

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()