pandas 透视表 pivot_table

简介: The function pandas.pivot_table can be used to create spreadsheet-style pivot tables.It takes a number of arguments    data: A DataFrame object    val...



The function pandas.pivot_table can be used to create spreadsheet-style pivot tables.

It takes a number of arguments

    data: A DataFrame object
    values: a column or a list of columns to aggregate
    index: a column, Grouper, array which has the same length as data, or list of them. Keys to group by on the pivot table index. If an array is passed, it is being used as the same manner as column values.
    columns: a column, Grouper, array which has the same length as data, or list of them. Keys to group by on the pivot table column. If an array is passed, it is being used as the same manner as column values.
    aggfunc: function to use for aggregation, defaulting to numpy.mean

    

import numpy as np
import pandas as pd
import datetime

df = pd.DataFrame({'A': ['one', 'one', 'two', 'three'] * 6,
                   'B': ['A', 'B', 'C'] * 8,
                   'C': ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'] * 4,
                   'D': np.random.randn(24),
                   'E': np.random.randn(24),
                   'F': [datetime.datetime(2013, i, 1) for i in range(1, 13)] +
                        [datetime.datetime(2013, i, 15) for i in range(1, 13)]})
                        

pd.pivot_table(df, index=['A', 'B'], columns=['C'], values='D', aggfunc=np.sum)

pd.pivot_table(df, index=['C'], columns=['A', 'B'], values='D', aggfunc='sum')

pd.pivot_table(df, index=['A', 'B'], columns=['C'], values=['D','E'], aggfunc=np.sum)

pd.pivot_table(df, index=['A', 'B'], columns=['C'], values=['D','E'], aggfunc=[np.sum])

pd.pivot_table(df, index=['A', 'B'], columns=['C'], values=['D','E'], aggfunc={'D':len,'E':np.sum})

pd.pivot_table(df, index=['A', 'B'], columns=['C'], values=['D','E'], aggfunc={'D':len,'E':[np.sum, np.mean]})

pd.pivot_table(df, index=pd.Grouper(freq='M', key='F'), columns='C', values='D', aggfunc=np.sum) # 有点类似 resample

 



 

目录
相关文章
|
SQL 关系型数据库 MySQL
使用Flink CDC从SQL Server同步数据到MySQL
使用Flink CDC从SQL Server同步数据到MySQL
1123 1
|
机器学习/深度学习 人工智能 算法
深度学习和强化学习有什么区别呢
【10月更文挑战第23天】深度学习和强化学习有什么区别呢
|
存储 监控 物联网
Doris实时数仓
Doris实时数仓
856 11
|
人工智能 数据管理 API
精铸智刃·“百炼”成钢——深度探索阿里云百炼大模型开发平台
阿里云百炼平台是一个一站式的大型语言模型开发和应用平台,旨在帮助企业与开发者高效构建和部署定制化的大模型。平台集成了通义大模型、行业模型和第三方模型,提供模型微调、模型调优、模型部署、模型评测等工具链。用户可以轻松创建和管理模型,通过模型广场选择合适的模型,进行模型体验和调优,然后部署模型以供应用调用。
74592 14
精铸智刃·“百炼”成钢——深度探索阿里云百炼大模型开发平台
|
资源调度 Kubernetes Java
Streampark使用体验与建议
Streampark使用体验与建议
531 0
|
1天前
|
云安全 人工智能 自然语言处理
|
6天前
|
搜索推荐 编译器 Linux
一个可用于企业开发及通用跨平台的Makefile文件
一款适用于企业级开发的通用跨平台Makefile,支持C/C++混合编译、多目标输出(可执行文件、静态/动态库)、Release/Debug版本管理。配置简洁,仅需修改带`MF_CONFIGURE_`前缀的变量,支持脚本化配置与子Makefile管理,具备完善日志、错误提示和跨平台兼容性,附详细文档与示例,便于学习与集成。
314 116
|
8天前
|
数据采集 人工智能 自然语言处理
Meta SAM3开源:让图像分割,听懂你的话
Meta发布并开源SAM 3,首个支持文本或视觉提示的统一图像视频分割模型,可精准分割“红色条纹伞”等开放词汇概念,覆盖400万独特概念,性能达人类水平75%–80%,推动视觉分割新突破。
600 53
Meta SAM3开源:让图像分割,听懂你的话