【Pandas】学习笔记之groupby()、agg()、transform()

在数据分析过程中经常需要对数据集进行分组,并且统计均值,最大值等等。那么 groupby() 的学习就十分有必要了


groupby(): 分组

官方文档:

python 复制代码
DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, observed=False, dropna=True)

A groupby operation involves some combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups.

Parameters:

  • by
  • axis
  • level
  • as_index
  • sort
  • group_keys
  • observed
  • dropna

Returns:
DataFrameGroupBy , Returns a groupby object that contains information about the groups.


生成一个学生数据集,包含身高和成绩:

python 复制代码
import pandas as pd
import numpy as np

classes = ["A", "B", "C"]

student = pd.DataFrame({
    'class': [classes[x] for x in np.random.randint(0,len(classes),10)],
    'height': np.random.randint(150, 190, 10),
    'score': np.random.randint(50, 100, 10)
    })

按班级分组:

python 复制代码
# 按班级分组
group = student.groupby('class')

# pandas.core.groupby.generic.DataFrameGroupBy
type(group)

list(group) 的结果是:

python 复制代码
Out[]: 
[('A',
    class  height  score  score_mean
  3     A     167     65   74.333333
  8     A     163     73   74.333333
  9     A     167     85   74.333333),
 ('B',
    class  height  score  score_mean
  1     B     175     76   59.666667
  6     B     151     53   59.666667
  7     B     185     50   59.666667),
 ('C',
    class  height  score  score_mean
  0     C     166     65        71.0
  2     C     185     61        71.0
  4     C     183     59        71.0
  5     C     182     99        71.0)]

可以看到,groupby的过程将整个df按照指定的字段分为若干个子df

之后的agg、apply等操作都是对子df的操作


agg(): 聚合操作

常见的有:

  • min最小值
  • max最大值
  • sum求和
  • mean求均值
  • count计数
  • median中位数
  • std标准差
  • var方差
python 复制代码
# 聚合操作之后的返回值类型为dataframe
a = student.groupby('class').agg('mean')
a = group.agg('mean')

# 可以用字典来指定对不用的列求不同的值
b = student.groupby('class').agg({'score':'mean','height':'median'})

a:

python 复制代码
Out[]: 
           height      score
class                       
A      165.666667  74.333333
B      170.333333  59.666667
C      179.000000  71.000000

b:

python 复制代码
Out[26]: 
           score  height
class                   
A      74.333333   167.0
B      59.666667   175.0
C      71.000000   182.5

transform()

agg() 是返回统计的结果,返回值为df
transform() 对每一条数据进行处理, 相同组有相同的结果, 组内求完均值后会按照原索引的顺序返回结果

返回series

如果要在student上加一列学生所在班级的平均分

不使用transform需要两步:

python 复制代码
# 1.先得到班级平均值的dict
avg_score_dict = student.groupby('class')['score'].mean().to_dict()
# 2.再对每个学生根据班级map一下
student['score_mean'] = student['class'].map(avg_score_dict)

使用transform只需要一步:

python 复制代码
student['score_mean'] = student.groupby('class')['score'].transform('mean')

apply():

能够传入任意自定义的函数,实现复杂的数据操作

注意:

  • groupby后的apply,以分组后的子DataFrame作为参数传入指定函数的,基本操作单位是DataFrame,而之前介绍的apply的基本操作单位是Series
  • apply拥有更大的灵活性,但运行效率会比agg和transform更慢

假设我需要获取每个班分数最高的学生的数据:

python 复制代码
# 获取分数最高的学生
def get_highest_student(x):
    df = x.sort_values(by='score', ascending=False)
    return df.iloc[0, :]

highest_student = student.groupby('class', as_index=False).apply(get_highest_student)
相关推荐
范纹杉想快点毕业1 天前
ZYNQ PS 端 UART 接收数据数据帧(初学者友好版)嵌入式编程 C语言 c++ 软件开发
c语言·笔记·stm32·单片机·嵌入式硬件·mcu·51单片机
茯苓gao1 天前
STM32G4 电流环闭环
笔记·stm32·单片机·嵌入式硬件·学习
easy20201 天前
机器学习的本质:从跑模型到真正解决问题
笔记·学习·机器学习
汇能感知1 天前
摄像头模组在智能家居设备中的应用
经验分享·笔记·科技
shizidushu1 天前
Graph RAG论文阅读笔记
论文阅读·笔记·graphrag
普蓝机器人1 天前
AutoTrack-IR-DR200仿真导航实验详解:为高校打造的机器人学习实践平台
人工智能·学习·机器人·移动机器人·三维仿真导航
0_0梅伊阁诗人1 天前
Django ORM 模型
开发语言·数据库·笔记·python·oracle·django
非凡ghost1 天前
AOMEI Partition Assistant磁盘分区工具:磁盘管理的得力助手
linux·运维·前端·数据库·学习·生活·软件需求
m0_578267861 天前
从零开始的python学习(九)P142+P143+P144+P145+P146
笔记·python·学习
非凡ghost1 天前
简朴App(PlainApp):开源、隐私保护的手机管理工具
学习·智能手机·生活·软件需求