df1 = pd.DataFrame({'fruit':['apple','banana','orange','apple','banana'],
'color':['red','yellow','yellow','cyan','cyan'],
'price':[8.5,6.8,5.6,7.8,6.4]})
#查看类型
type(df1.groupby('fruit'))
pandas.core.groupby.groupby.DataFrameGroupBy #GruopBy对象,它是一个包含组名,和数据块的2维元组序列,支持迭代
for name, group in df1.groupby('fruit'):
print(name) #输出组名
apple
banana
orange
print(group) # 输出数据块
fruit color price
0 apple red 8.5
3 apple cyan 7.8
fruit color price
1 banana yellow 6.8
4 banana cyan 6.4
fruit color price
2 orange yellow 5.6
#输出group类型
print(type(group)) #数据块是dataframe类型
<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>
#选择任意的数据块
dict(list(df1.groupby('fruit')))['apple'] #取出apple组的数据块
fruit color price
0 apple red 8.5
3 apple cyan 7.8