Pandas实现聚合运算agg()的示例代码
作者:ZSYL 时间:2023-09-27 12:35:49
前言
在数据分析中,分组聚合二者缺一不可。对数据聚合(求和、平均值等)通常是不可避免的。pd.agg()
很方便进行聚合操作。
1. 创建DataFrame对象
import pandas as pd
df1 = pd.DataFrame({'sex':list('FFMFMMF'),'smoker':list('YNYYNYY'),'age':[21,30,17,37,40,18,26],'weight':[120,100,132,140,94,89,123]})
grouped = df1.groupby(['sex','smoker'])
# sex有 F M 二值,smoker有 Y N 二值,故分成四组。
2. 单列聚合
grouped['age'].agg('mean')
sex smoker
F N 30.0
Y 28.0
M N 40.0
Y 17.5
Name: age, dtype: float64
3. 多列聚合
grouped.agg('mean')
4. 多种聚合运算
grouped['age'].agg(['min','max'])
5. 多种聚合运算并更改列名
grouped['age'].agg([('A','mean'),('B','max')])
6. 不同的列运用不同的聚合函数
grouped.agg({'age':['sum','mean'], 'weight':['min','max']})
7. 使用自定义的聚合函数
def Max_cut_Min(group):
return group.max()-group.min()
grouped.agg(Max_cut_Min)
8. 方便的descibe
grouped.describe()
参考博客:link
来源:https://blog.csdn.net/qq_46092061/article/details/119189104
标签:Pandas,聚合运算,agg()
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python正则表达式之re.match()与re.search()的用法及区别
2022-05-14 13:21:46
Python paramiko模块使用解析(实现ssh)
2021-02-03 10:29:26
Python标准库之time库的使用教程详解
2023-07-25 05:25:57
![](https://img.aspxhome.com/file/2023/2/61702_0s.jpg)
Python学习之自定义异常详解
2021-05-05 18:46:20
Python记录详细调用堆栈日志的方法
2023-11-16 17:20:57
Python获取对象属性的几种方式小结
2022-05-27 18:09:42
ASP中双引号单引号和&连接符使用技巧
2007-10-01 18:20:00
Golang中struct{}和struct{}{}的区别解析
2024-04-23 09:36:21
2007流行网站导航设计欣赏
2008-02-18 12:20:00
![](https://img.aspxhome.com/file/UploadPic/20082/18/2008218122731730s.jpg)
python使用scapy模块实现ARP扫描的过程
2023-07-16 11:55:26
![](https://img.aspxhome.com/file/2023/0/85070_0s.png)
浅谈python中的@以及@在tensorflow中的作用说明
2021-06-10 01:50:22
python绘制散点图和折线图的方法
2021-08-24 04:27:56
![](https://img.aspxhome.com/file/2023/4/93624_0s.jpg)
实例详解Python装饰器与闭包
2021-05-27 10:12:21
nestjs实现图形校验和单点登录的示例代码
2024-04-16 09:49:08
![](https://img.aspxhome.com/file/2023/8/136548_0s.gif)
PyQt5+QtChart实现绘制区域图
2021-08-15 01:00:05
![](https://img.aspxhome.com/file/2023/0/135360_0s.png)
vue具名插槽的基本使用实例
2024-04-27 15:51:16
![](https://img.aspxhome.com/file/2023/7/133097_0s.png)
将各种类型或对象都转变为数组
2009-12-28 13:19:00
Python 简单计算要求形状面积的实例
2022-10-19 09:02:33
![](https://img.aspxhome.com/file/2023/2/135122_0s.jpg)
mysql索引基数概念与用法示例
2024-01-27 05:43:51
ASP中Session技巧 默认过期时间为20分钟
2012-12-04 20:28:26