groupby
是pandas
中非常重要的一个函数, 主要用于数据聚合和分类计算. 其思想是“split-apply-combine”
(拆分 - 应用 - 合并).
- 拆分:
groupby
,按照某个属性column
分组,得到的是一个分组之后的对象- 应用:对上面的对象使用某个函数,可以是自带的也可以是自己写的函数,通过
apply(function)
- 合并:最终结果是个S型数据
官方文档
DataFrame.``groupby
(self, by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, observed=False, **kwargs)
常用参数
- by : mapping, function, label, or list of labels
- axis : {0 or ‘index’, 1 or ‘columns’}, default 0;Split along rows (0) or columns (1).
- level : int, level name, or sequence of such, default None
- as_index : bool, default True
- sort : bool, default True。默认是情况下会对数据进行分组,关闭可以提高性能
- group_keys : bool, default True
by和as_index最常用
返回值
DataFrameGroupBy or SeriesGroupBy
Depends on the calling object and returns groupby object that contains information about the groups.
demo
groupby
后面接上分组的列属性名称(单个)- 多个属性用列表形式表示,形成层次化索引
1 |
In [1]: df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar', |
栗子
导入数据
1 |
import numpy as np |
现有数据特点
- user_id: id号
- age: 年龄
- gender: 性别
- occupation: 职业
- zip_code: 邮政编码, 通过邮政编码可获取所在城市
解决问题
- 如何找出每一种职业的平均年龄?(需要按照职业进行分组)并按照平均年龄从大到小排序?(分组之后对年龄求平均再排序)
- 分别找出男人和女人每种职业的人数?(按照男女分组)
- 更进一步, 如何找出男人和女人在不同职业的平均年龄?(先按男女分组,再按照不同职业分组,再求平均年龄)
问题1 : 如何找出每一种职业的平均年龄?并按照平均年龄从大到小排序?
- 分组用
groupby
- 求平均
mean()
- 排序
sort_values
,默认是升序asc
- 操作某个列属性,通过属性的方式
df.column
1 |
df.groupby("occupation").age.mean().sort_values(ascending=False) # 默认是升序 |
- 首先
df
按照每一种occupation
拆分成多个部分 - 然后分别计算每种
occupation
的age
的平均值 - 最后合并成一个
Dataframe
或者Series
- 值得注意的是,
groupby
之后是一个对象,,直到应用一个函数(mean函数)之后才会变成一个Series
或者Dataframe
.
1 |
type(df.groupby("occupation")) |
问题2 : 分别找出男人和女人每种职业的人数?
- 对两个属性同时进行分组
- 再进行
size
函数求和
1 |
df.groupby(['occupation','gender']).size() |
问题3 : 如何找出男人和女人在不同职业的平均年龄?
- 先对职业和性别机型分组
- 再对年龄求平均值
1 |
df.groupby(['occupation','gender']).age.mean() |
问题4:两个列属性的groupby机制
-
栗子中按照性别
gender
分组groupby
,再求职业的总和size
1
2
3
4
5
6
7df['occupation'].groupby(df['gender']).size()
# result
gender
F 273
M 670
Name: occupation, dtype: int64 -
按照职业分组
groupby
,再对年龄求平均值mean
1
2
3
4
5
6
7
8
9
10
11
12df['age'].groupby(df['occupation']).mean()
# result
occupation
administrator 38.746835
artist 31.392857
doctor 43.571429
educator 42.010526
engineer 36.388060
entertainment 29.222222
executive 38.718750
......
groupby
细说
最常用参数
- by:可以是列属性
column
,也可以是和df
同行的Series
- as_index:是否将
groupby
的column
作为index
, 默认是True
groupby之后的对象应用自定义的函数
1 |
demo = df[:5] |
有个DF
数据出现了两次,解释看Stack Overflow
分组之后的操作
1 |
# 分组之后进行遍历 |
避免层次化索引
- 分组和聚合之后使用
reset_index()
- 在分组时,使用
as_index=False
1 |
# 1 |
近期评论