Pandas GroupBy对象
创建GroupBy对象
GroupBy对象可以通过pandas.DataFrame.groupby(), pandas.Series.groupby()来创建。
GroupBy = DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, **kwargs)[source]
参数 | 描述 |
---|---|
by | mapping, function, str, or iterable |
axis | int, default 0 |
level | int, level name, or sequence of such, default None(复合索引的时候指定索引层级) |
as_index | boolean, default True(by列当成索引) |
sort | boolean, default True(排序) |
group_keys | boolean, default True(?) |
squeeze | boolean, default False(?) |
参数说明:
1.as_index
默认会把groupby的key当成索引,不太符合sql的习惯,可以设置为False
import pandas as pd
import numpy as np
df = pd.DataFrame({'A' : [1, 1, 2, 2,1, 2, 2, 2],'B' : [15,14,15,12,13,14,15,16]})
df.groupby("A").sum()
out:B
A
1 42
2 72df.groupby("A", as_index=False).sum()
df.groupby("A").sum().reset_index() # 和as_index=False等效
out:A B
0 1 42
1 2 72
索引与迭代
groupby是一个迭代对象,每个元素是分组后的小数据框.
属性 | 描述 |
---|---|
GroupBy.iter() | Groupby iterator |
GroupBy.groups | dict {group name -> group labels} |
GroupBy.indices | dict {group name -> group indices} |
GroupBy.get_group(name[, obj]) | Constructs NDFrame from group with provided name |
Grouper([key, level, freq, axis, sort]) | A Grouper allows the user to specify a groupby instruction for a target |
函数应用(Function application)
- GroupBy.apply(func, *args, **kwargs)apply函数是对迭代对象每个小数据框进行作用,可以调用dataframe的所有方法
- GroupBy.aggregate(func, *args, **kwargs)聚合函数可以传入
np.sum
或者"sum"
等聚合参数,在描述统计中的函数,其实都是在调用agg
(简写形式)函数 - GroupBy.transform(func, *args, **kwargs)
- filter
描述统计
##数据框(DataFrame)与序列(Series)通用函数
Function | Describe |
---|---|
统计函数 | |
GroupBy.sum() | 计算每组的和 |
GroupBy.ohlc() | Compute sum of values, excluding missing values |
GroupBy.cumcount([ascending]) | Number each item in each group from 0 to the length of that group - 1. |
GroupBy.mean(*args, **kwargs) | 均值,不包含缺失值 |
GroupBy.prod() | Compute prod of group values |
GroupBy.var([ddof]) | 方差,不包含缺失值 |
GroupBy.std([ddof]) | 标准差,不包含缺失值 |
GroupBy.sem([ddof]) | 标准误,不包含缺失值 |
GroupBy.size() | 组大小 |
GroupBy.count() | 组元素个数,不包含缺失值 |
GroupBy.max() | 组最大值 |
GroupBy.min() | 组最小值 |
GroupBy.median() | 组中间值 |
索引函数 | |
GroupBy.first() | Compute first of group values |
GroupBy.head([n]) | Returns first n rows of each group. |
GroupBy.last() | Compute last of group values |
GroupBy.tail([n]) | Returns last n rows of each group |
GroupBy.nth(n[, dropna]) | 每组第n条数据 |
数据框(DataFrame)与序列(Series)不一致函数
Function | Describe |
---|---|
DataFrameGroupBy.agg(arg,?*args,?**kwargs) | Aggregate using input function or dict of {column -> |
DataFrameGroupBy.all([axis,?bool_only,?..]) | Return whether all elements are True over requested axis |
DataFrameGroupBy.any([axis,?bool_only,?..]) | Return whether any element is True over requested axis |
DataFrameGroupBy.bfill([limit]) | Backward fill the values |
DataFrameGroupBy.corr([method,?min_periods]) | Compute pairwise correlation of columns, excluding NA/null values |
DataFrameGroupBy.count() | Compute count of group, excluding missing values |
DataFrameGroupBy.cov([min_periods]) | Compute pairwise covariance of columns, excluding NA/null values |
DataFrameGroupBy.cummax([axis,?skipna]) | Return cumulative max over requested axis. |
DataFrameGroupBy.cummin([axis,?skipna]) | Return cumulative minimum over requested axis. |
DataFrameGroupBy.cumprod([axis]) | Cumulative product for each group |
DataFrameGroupBy.cumsum([axis]) | Cumulative sum for each group |
DataFrameGroupBy.describe([percentiles,?..]) | Generate various summary statistics, excluding NaN values. |
DataFrameGroupBy.diff([periods,?axis]) | 1st discrete difference of object |
DataFrameGroupBy.ffill([limit]) | Forward fill the values |
DataFrameGroupBy.fillna([value,?method,?..]) | Fill NA/NaN values using the specified method |
DataFrameGroupBy.hist(data[,?column,?by,?..]) | Draw histogram of the DataFrame’s series using matplotlib / pylab. |
DataFrameGroupBy.idxmax([axis,?skipna]) | Return index of first occurrence of maximum over requested axis. |
DataFrameGroupBy.idxmin([axis,?skipna]) | Return index of first occurrence of minimum over requested axis. |
DataFrameGroupBy.mad([axis,?skipna,?level]) | Return the mean absolute deviation of the values for the requested axis |
DataFrameGroupBy.pct_change([periods,?..]) | Percent change over given number of periods. |
DataFrameGroupBy.plot | Class implementing the .plot attribute for groupby objects |
DataFrameGroupBy.quantile([q,?axis,?..]) | Return values at the given quantile over requested axis, a la numpy.percentile. |
DataFrameGroupBy.rank([axis,?method,?..]) | Compute numerical data ranks (1 through n) along axis. |
DataFrameGroupBy.resample(rule,?*args,?**kwargs) | Provide resampling when using a TimeGrouper |
DataFrameGroupBy.shift([periods,?freq,?axis]) | Shift each group by periods observations |
DataFrameGroupBy.size() | Compute group sizes |
DataFrameGroupBy.skew([axis,?skipna,?level,?..]) | Return unbiased skew over requested axis |
DataFrameGroupBy.take(indices[,?axis,?..]) | Analogous to ndarray.take |
DataFrameGroupBy.tshift([periods,?freq,?axis]) | Shift the time index, using the index’s frequency if available. |
仅支持序列(Series)的函数
Function | Describe |
---|---|
SeriesGroupBy.nlargest(*args,?**kwargs) | Return the largest?n?elements. |
SeriesGroupBy.nsmallest(*args,?**kwargs) | Return the smallest?n?elements. |
SeriesGroupBy.nunique([dropna]) | Returns number of unique elements in the group |
SeriesGroupBy.unique() | Return np.ndarray of unique values in the object. |
SeriesGroupBy.value_counts([normalize,?..]) |
仅支持数据框(DataFrame)的函数
Function | Describe |
---|---|
DataFrameGroupBy.corrwith(other[,?axis,?drop]) | Compute pairwise correlation between rows or columns of two DataFrame objects. |
DataFrameGroupBy.boxplot(grouped[,?..]) | Make box plots from DataFrameGroupBy data. |
Pandas GroupBy对象相关推荐
- Pandas GroupBy对象 索引与迭代
import pandas as pd df = pd.DataFrame({'性别' : ['男', '女', '男', '女','男', '女', '男', '男'],'成绩' : ['优秀', ...
- python画熊猫代码_python – 使用子图和循环绘制Pandas groupby组
我正在尝试基于Pandas groupby对象生成子图的网格.我希望每个绘图都基于groupby对象的一组的两列数据.假数据集: C1,C2,C3,C4 1,12,125,25 2,13,25,25 ...
- collector list 多个分组_【S01E07】groupby方法、GroupBy对象、groupby方法的分组键
Hadley Wickham(许多热门R语言包的作者)创造了一个用于表示分组运算的术语"split-apply-combine"(拆分-应用-合并),这个词很好的描述了整个过程.分 ...
- Pandas GroupBy 深度总结
今天,我们将探讨如何在 Python 的 Pandas 库中创建 GroupBy 对象以及该对象的工作原理.我们将详细了解分组过程的每个步骤,可以将哪些方法应用于 GroupBy 对象上,以及我们可以 ...
- 【Python】Pandas GroupBy 深度总结
今天,我们将探讨如何在 Python 的 Pandas 库中创建 GroupBy 对象以及该对象的工作原理.我们将详细了解分组过程的每个步骤,可以将哪些方法应用于 GroupBy 对象上,以及我们可以 ...
- 使用pandas GroupBy获取每个组的统计信息(例如计数,均值等)?
本文翻译自:Get statistics for each group (such as count, mean, etc) using pandas GroupBy? I have a data f ...
- pandas python groupby_python – pandas groupby方法实际上是如何工作的?
当你使用时 df.groupby('A') 你得到一个groupby object.你还没有应用任何功能.在引擎盖下,虽然这个定义可能不完美,但您可以将groupby对象视为: >(group, ...
- itertools.groupby与pandas.groupby的异同
背景 最近遇到一个bug,是在老代码中,多年用下来都没事,但是新增业务需求就遇到问题了.经过排除,发现是由于itertools.groupby的用法与想象中不一样,至少与我熟知的pandas.grou ...
- pandas—groupby如何得到分组里的数据
pandas-groupby如何得到分组里的数据 有的时候csv文件过大,利用循环时间消耗大,因此可以通过分组. 原数据如下: 想把link和future特征为基准,把current整合起来放在一列. ...
最新文章
- MongoDB 3.0 WiredTiger Compression and Performance
- python提取个十百千位数字_实现人脸识别、人脸68个特征点提取,或许这个 Python 库能帮到你!...
- Spring Boot 注册 Servlet 的3种方式
- java使用xml存储数据_聊一聊 Redis 数据内部存储使用到的数据结构
- 一? ilkkn.n_IL&FS的完整形式是什么?
- python自增_Python的自增运算与Python变量的浅析
- linux打开pythonshall,linux系统shell脚本后台运行python程序
- c# 打开的窗口显示在最前面_了解各种切换程序窗口的方法,提高工作效率
- .htaccess跳转https
- 【自学笔记】基于R语言的copula函数重现期等值线绘制
- Microsoft® Silverlight™ Streaming by Windows Live™
- Atitit 木马病毒自动启动-------------win7计划任务的管理
- 1月英语总结—发现新大陆
- 【SpringBoot高级篇】springboot实现上传docdocx文件格式转pdf在线预览
- SAP 系统销售流程成本和收入的确认
- python网络爬虫-淘宝商品比价定向爬虫
- 微信小程序 全局状态管理 ,响应式
- 全新安装Windows10系统(PE下)
- 【OpenGL】笔记三、着色器
- 推荐35个非常有创意的404错误页面
热门文章
- egg extend ts_电竞5.21日王者荣耀KPL分析:DYG冲击西部榜首,TS战队能否虐菜?
- Python+pywin32操作Excel文件常用功能(268行代码+注释)
- Python中带else子句的for循环执行过程
- ajax注册用户名为空,怎么用ajax和js检测用户名是否合法和不能为空
- 计算机中常见的英语错误提示,BIOS出错英文提示信息大全 -电脑资料
- python opencv显示图片一闪而过_解决Opencv+Python cv2.imshow闪退问题
- jwt判断token是否过期_4spring-security5整合jwt做登录、权限验证,全网最全!!!可用...
- 用户操作计算机的方法,操作者向计算机输入信息最常用的方法是(B).doc
- bootstrap 导航栏 字体 颜色_设计自己的Hugo主题——开发导航栏
- explode php,php中的explode()函数实例介绍