Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何按分组索引访问pandas groupby数据帧?_Python_Python 3.x_Pandas_Pandas Groupby - Fatal编程技术网

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

Python 如何按分组索引访问pandas groupby数据帧?,python,python-3.x,pandas,pandas-groupby,Python,Python 3.x,Pandas,Pandas Groupby,下面我可以创建一个简单的dataframe和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':

下面我可以创建一个简单的dataframe和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'})
结果是分组的数据帧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]
我还想按分组指数进行绘图。类似于

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

     A  B
0  bar  7
绘图:

import matplotlib.pyplot as plt

plt.bar(gf.A, gf.B)
那么:

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