Python之Pandas超详细入门教程 -- 第七章 Pandas分组与聚合【进阶篇】

it2024-04-20  5

分组与聚合通常是分析数据的一种方式,通常与一些统计函数一起使用,查看数据的分组情况

1 什么分组与聚合

2 分组API

DataFrame.groupby(key, as_index=False) 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 # 分组,数据的结构不变 col.groupby(['color'], as_index=False)['price1'].mean() color price1 0 green 2.025 1 red 2.380 2 white 5.560

3 案例星巴克零售店铺数据

3.1 数据获取

从文件中读取星巴克店铺数据

# 导入星巴克店的数据 starbucks = pd.read_csv("./data/starbucks/directory.csv")

3.2 进行分组聚合

# 按照国家分组,求出每个国家的星巴克零售店数量 country_count = starbucks.groupby(["Country"])["Brand"].count() # 对每个国家的星巴克数量降序排序,并取前20个 country_count = country_count.sort_values(ascending = False).head(20) # 将前20名数据绘制成柱状图显示 country_count.plot(kind = "bar", figsize = (15,8)) plt.show()

创作不易,白嫖不好,各位的支持和认可,就是我创作的最大动力,我们下篇文章见!

Dragon少年 | 文

如果本篇博客有任何错误,请批评指教,不胜感激 !

最新回复(0)