Fork me on GitHub

python-for-data-groupby使用和透视表

第十章主要讲解的数据聚合与分组操作。对数据集进行分类,并在每一个组上应用一个聚合函数或者转换函数,是常见的数据分析的工作。

本文结合pandas官方文档整理而来。

groupby机制

组操作的术语:拆分-应用-联合split-apply-combine。分离是在特定的轴上进行的,axis=0表示行,axis=1表示列。

  • Splitting the data into groups based on some criteria.
  • Applying a function to each group independently.
  • Combining the results into a data structure.

分组聚合示意图

groupby参数

Parameters参数

  • **by:**mapping, function, label, or list of labels

    Used to determine the groups for the groupby. If by is a function, it’s called on each value of the object’s index. If a dict or Series is passed, the Series or dict VALUES will be used to determine the groups (the Series’ values are first aligned; see .align() method). If an ndarray is passed, the values are used as-is determine the groups. A label or list of labels may be passed to group by the columns in self. Notice that a tuple is interpreted as a (single) key.

  • 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

    If the axis is a MultiIndex (hierarchical), group by a particular level or levels.

  • as_index:bool, default True

    For aggregated output, return object with group labels as the index. Only relevant for DataFrame input. as_index=False is effectively “SQL-style” grouped output.

  • sort:bool, default True

    Sort group keys. Get better performance by turning this off. Note this does not influence the order of observations within each group. Groupby preserves the order of rows within each group.

  • group_keys:bool, default True

    When calling apply, add group keys to index to identify pieces.

  • squeeze:bool, default False

    Reduce the dimensionality of the return type if possible, otherwise return a consistent type.

  • observed:bool, default False

    This only applies if any of the groupers are Categoricals. If True: only show observed values for categorical groupers. If False: show all values for categorical groupers.New in version 0.23.0.

Returns返回值

  • DataFrameGroupBy

    Returns a groupby object that contains information about the groups.

分组键

分组键可以是多种形式,并且键不一定是完全相同的类型:

  1. 与需要分组的轴向长度一致的值列表或者值数组
  2. DataFrame列名的值
  3. 可以在轴索引或索引中的单个标签上调用的函数
  4. 可以将分组轴向上的值和分组名称相匹配的字典或者Series

特点

  • 分组键可以是正确长度的任何数组
  • 通用的groupby方法是size,返回的是一个包含组大小信息的Series
  • 分组中的任何缺失值将会被排除在外
  • 默认情况下,groupby是在axis=0情况下进行的

语法糖现象:

1
2
3
df.groupby('key1')['data1']

df['data1'].groupby(df['key1'])
  • 如果传递的是列表或者数组,返回的是分组的DataFrame;如果传递的是单个列名,则返回的是Series
1
2
3
df.groupby(['key1','key2'])[['data2']].mean()  # 传递列表形式

df.groupby(['key1','ley2'])['data2'].mean() # 传递的是单个列名

数据聚合

聚合指的是所有根据数组产生标量值的数据转换过程。常见的聚合函数:

  1. count

  2. sum

  3. mean

  4. median

  5. std、var

  6. min、max

  7. prod

  8. fisrt、last

  9. 如果想使用自己的聚合函数,可以将函数传递给aggregate或者agg方法

笔记1:自定义的聚合函数通常比较慢,需要额外的开销:函数调用、数据重新排列等

1
2
3
4
5
6
7
8
import numpy as np
import pandas as pd
tips = pd.read_csv(path)
tips['tip_pct'] = tips['tip'] / tips['total_bill']

grouped = tips.groupby(['day','smoker']) # 根据两个属性先分组
grouped_pct = grouped['tip_pct']
grouped_pct.agg('mean') # 函数名通过字符串的形式传递
  1. 如果传递的是函数或者函数名的列表,则生成的DF数据的列名将会是这些函数名:

  1. 如果传递的是(name,function)形式,则每个元组的name将会被作为DF数据的列名:

  1. 不同的函数应用到一个或者多个列上

笔记2:只有当多个函数应用到至少一个列时,DF才具有分层列

  1. 返回不含行索引的聚合数据:通过向groupby传递as_index=False来实现

数据透视表和交叉表

DF中的pivot-table方法能够实现透视表,默认求的是平均值mean交叉表是透视表的特殊情况

另一种方法:groupby+mean

透视表中常用的几个参数:

  • index:行索引
  • columns:列属性
  • aggfunc:聚合函数
  • fill_value:填充NULL值
  • margins :显示ALL属性或者索引

Groupby Dataframe with Index levels and columns

三种不同的方式来实现

1
2
3
df.groupby([pd.Grouper(level=1), 'A']).sum()
# df.groupby([pd.Grouper(level='second'), 'A']).sum()
# df.groupby(['second', 'A']).sum()

一图看懂透视表

本文标题:python-for-data-groupby使用和透视表

发布时间:2020年04月09日 - 19:04

原始链接:http://www.renpeter.cn/2020/04/09/python-for-data-groupby.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Coffee or Tea