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