1 分组API
- DataFrame.groupby(key, as_index=False)
- key:分组的列数据,可以多个
案例:不同颜色的不同笔的价格数据
- key:分组的列数据,可以多个
col =pd.DataFrame({'color': ['white','red','green','red','green'], 'object': ['pen','pencil','pencil','ashtray','pen'],'price1':[5.56,4.20,1.30,0.56,2.75],'price2':[4.75,4.12,1.60,0.75,3.15]})
color object price1 price2
0 white pen 5.56 4.75
1 red pencil 4.20 4.12
2 green pencil 1.30 1.60
3 red ashtray 0.56 0.75
4 green pen 2.75 3.15
进行分组,对颜色分组,price进行聚合
# 分组,求平均值
col.groupby(['color'])['price1'].mean()
col['price1'].groupby(col['color']).mean()
color
green 2.025
red 2.380
white 5.560
Name: price1, dtype: float64
2 案例
# 导入星巴克店的数据
starbucks = pd.read_csv("./data/starbucks/directory.csv")
# 按照国家分组,求出每个国家的星巴克零售店数量
count = starbucks.groupby(['Country']).count()
# 设置多个索引,set_index()
starbucks.groupby(['Country', 'State/Province']).count()
#画图显示结果
count['Brand'].plot(kind='bar', figsize=(20, 8))
plt.show()
注:pandas中,分组之后(groupby),必须要聚合(mean)