系列文章目录
第一章 Pandas 学习入门之pandas数据读取
第二章 Pandas 学习入门之pandas数据结构
第三章 Pandas 学习入门之pandas数据查询
第四章 Pandas 学习入门之pandas新增数据列
第五章 Pandas 学习入门之pandas数据统计函数
第六章 Pandas 学习入门之pandas处理缺失值
第七章 Pandas 学习入门之pandas数据排序
第八章 Pandas 学习入门之pandas字符串操作
第九章 Pandas 学习入门之pandas重要参数axis
第十章 Pandas 学习入门之pandas索引index用途
第十一章 Pandas 学习入门之pandas实现DataFrame的Merge
第十二章 Pandas 学习入门之pandas实现数据合并Concat
第十三章 Pandas 学习入门之pandas批量拆分Excel与合并Excel
第十四章 Pandas 学习入门之pandas分组聚合统计groupby
随着人工智能的不断发展,数据分析这门技术也越来越重要,很多人都开启了学习数据分析,本文就介绍了pandas学习的基础内容。本章简单介绍了pandas分组聚合统计,具体介绍了分组使用聚合函数做数据统计和遍历groupby的结果执行流程两种方法
。
前言
本章简单介绍了pandas分组聚合统计,具体介绍了分组使用聚合函数做数据统计和遍历groupby的结果执行流程两种方法
。
提示:以下是本篇文章正文内容,下面案例可供参考
一、pandas怎样实现groupby分组统计?
类似SQL:
SQL:select city,max(temperature) from city_weather group by city;
groupby:先对数据分组,然后在每个分组上应用聚合函数、转换函数
二、引入库 & 数据准备
1.引入库
代码如下(示例):
import pandas as pd
import numpy as np
# 加上这一句,能在jupyter notebook展示matplot图表
%matplotlib inline
2.数据准备
df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
'C': np.random.randn(8),
'D': np.random.randn(8)})
df
A | B | C | D | |
0 | foo | one | -0.3024 | 1.345 |
1 | bar | one | 1.2562 | -0.5394 |
2 | foo | two | -1.5419 | 0.2864 |
3 | bar | three | 0.2863 | -1.4856 |
4 | foo | two | -0.6789 | -1.6523 |
5 | bar | two | 1.8896 | 0.6302 |
6 | foo | one | -0.5771 | 0.6355 |
7 | foo | three | 0.5285 | -0.2845 |
三、分组使用聚合函数做数据统计
1.单个列groupby,查询所有数据列的统计
df.groupby('A').sum()
-
分组:根据列 'A' 的值,DataFrame 被分成两组 —— 'foo' 组和 'bar' 组。
-
求和:对于每个分组,计算 'C' 和 'D' 列的总和。
-
结果:得到的结果是一个新的DataFrame,它只包含数值列('C' 和 'D')的分组总和,索引则是列 'A' 中用作分组依据的唯一值。
- 因为要统计sum,但B列不是数字,所以被自动忽略掉。
2.多个列groupby,查询所有数据列的统计
df.groupby(['A','B']).mean()
我们看到:('A','B')成对变成了二级索引。
df.groupby(['A','B'], as_index=False).mean()
as_index=False
:这个参数是groupby
方法的一个重要选项。当设置为False
时,它指示Pandas不要使用分组键作为返回DataFrame的索引。这意味着分组键(在本例中是'A'
和'B'
)将作为普通的列返回,而不是作为索引。这样做通常使结果更易于理解和进一步处理,因为每行都明确包含了用于分组的值。
3.同时查看多种数据统计
df.groupby('A').agg([np.sum, np.mean, np.std])
我们看到:列变成了多级索引。
4.查看单列的结果数据统计
# 方法1:预过滤,性能更好
df.groupby('A')['C'].agg([np.sum, np.mean, np.std])
# 方法2
df.groupby('A').agg([np.sum, np.mean, np.std])['C']
5.不同列使用不同的聚合函数
df.groupby('A').agg({"C":np.sum, "D":np.mean})
四、遍历groupby的结果理解执行流程
for循环可以直接遍历每个group
1.遍历单个列聚合的分组
g = df.groupby('A')
g
<pandas.core.groupby.generic.DataFrameGroupBy object at 0x000002CD38B33670>
for name,group in g:
print(name)
print(group)
print()
bar A B C D 1 bar one -1.622890 2.564019 3 bar three -0.588045 0.060391 5 bar two 0.950955 0.979372 foo A B C D 0 foo one -0.839845 0.483710 2 foo two -1.780685 -1.130024 4 foo two -1.738213 0.116095 6 foo one -1.009902 0.069287 7 foo three 0.191275 -0.565694
df
是之前创建的DataFrame,那么g
是按照列'A'对df
进行分组的DataFrameGroupBy
对象。在这个例子中,列'A'有两个唯一值:'foo' 和 'bar'。
当执行上述循环时,你将会看到类似以下内容:
- 首先,
name
变量会是'bar',group
变量则包含所有列'A'值为'bar'的行。- 然后,
name
变量会是'foo',group
变量包含所有列'A'值为'foo'的行。- 对于每个分组,循环都会打印分组的名称和属于该分组的数据。这样做非常有助于理解数据是如何被分组的,以及每个分组内包含哪些数据。
1.1 可以获取单个分组的数据
g.get_group('bar')
2.遍历多个列聚合的分组
g = df.groupby(['A', 'B'])
for name,group in g:
print(name)
print(group)
print()
('bar', 'one') A B C D 1 bar one -1.62289 2.564019 ('bar', 'three') A B C D 3 bar three -0.588045 0.060391 ('bar', 'two') A B C D 5 bar two 0.950955 0.979372 ('foo', 'one') A B C D 0 foo one -0.839845 0.483710 6 foo one -1.009902 0.069287 ('foo', 'three') A B C D 7 foo three 0.191275 -0.565694 ('foo', 'two') A B C D 2 foo two -1.780685 -1.130024 4 foo two -1.738213 0.116095
!! 可以看到,name是一个2个元素的tuple,代表不同的列!!
g.get_group(('foo', 'one'))
2.1 可以直接查询group后的某几列,生成Series或者子DataFrame
g['C']
<pandas.core.groupby.generic.SeriesGroupBy object at 0x000002CD38B335B0>
for name, group in g['C']:
print(name)
print(group)
print(type(group))
print()
('bar', 'one') 1 -1.62289 Name: C, dtype: float64 <class 'pandas.core.series.Series'> ('bar', 'three') 3 -0.588045 Name: C, dtype: float64 <class 'pandas.core.series.Series'> ('bar', 'two') 5 0.950955 Name: C, dtype: float64 <class 'pandas.core.series.Series'> ('foo', 'one') 0 -0.839845 6 -1.009902 Name: C, dtype: float64 <class 'pandas.core.series.Series'> ('foo', 'three') 7 0.191275 Name: C, dtype: float64 <class 'pandas.core.series.Series'> ('foo', 'two') 2 -1.780685 4 -1.738213 Name: C, dtype: float64 <class 'pandas.core.series.Series'>
其实所有的聚合统计,都是在dataframe和series上进行的。
五、实例分组探索天气数据
1.数据准备
df = pd.read_csv("./beijing_tianqi_2018.csv")
# 替换掉温度的后缀℃
df.loc[:, "bWendu"] = df["bWendu"].str.replace("℃", "").astype('int32')
df.loc[:, "yWendu"] = df["yWendu"].str.replace("℃", "").astype('int32')
df.head()
# 新增一列为月份
df['month'] = df['ymd'].str[:7]
df.head()
2.查看每个月的最高温度
data = df.groupby('month')['bWendu'].max()
data
month 2018/1 25 2018/2 12 2018/3 27 2018/4 30 2018/5 35 2018/6 38 2018/7 37 2018/8 36 2018/9 31 Name: bWendu, dtype: object
type(data)
pandas.core.series.Series
data.plot()
%matplotlib inline
魔法命令仅需要在Jupyter Notebook中运行一次,它会应用到整个笔记本中的所有单元格。在这里需要使用df.plot()
来显示图表。
3.查看每个月的最高温度、最低温度、平均空气质量指数
df.head()
group_data = df.groupby('month').agg({"bWendu":np.max, "yWendu":np.min, "aqi":np.mean})
group_data
group_data.plot()
%matplotlib inline
魔法命令仅需要在Jupyter Notebook中运行一次,它会应用到整个笔记本中的所有单元格。在这里需要使用df.plot()
来显示图表。
如果你希望在笔记本外部的其他环境中(例如一个Python脚本或终端)运行相同的代码,那么就不需要使用
%matplotlib inline
命令。在那些环境中,你可能需要使用plt.show()
来显示图表。
总结
提示:这里对文章进行总结:
随着人工智能的不断发展,数据分析这门技术也越来越重要,很多人都开启了学习数据分析,本文就介绍了pandas学习的基础内容。本章简单介绍了pandas分组聚合统计,具体介绍了分组使用聚合函数做数据统计和遍历groupby的结果执行流程两种方法
。