Fork me on GitHub

一文看懂pandas中的透视表

一文看懂pandas中的透视表

读取数据

1
2
3
4
5
import pandas as pd
import numpy as np

df = pd.read_excel("./sales-funnel.xlsx") # 当前目录下的文件
df.head()

设置数据

使用category数据类型,按照想要查看的方式设置顺序

不严格要求,但是设置了顺序有助于分析,一直保持所想要的顺序

1
2
df["Status"] = df["Status"].astype("category")
df["Status"].cat.set_categories(["won","pending","presented","declined"],inplace=True) # 设置顺序

建立透视表

  1. 只使用index参数
1
pd.pivot_table(df,index=["Manager","Rep"])  # index表示索引

  1. 使用index和values两个参数

  1. 使用aggfunc参数,指定多个函数

4.使用columns参数,指定生成的列属性

  1. 解决数据的NaN值,使用fill_value参数

  1. 查看总数据,使用margins=True

  1. 不同的属性字段执行不同的函数

image-20200426093414531

  1. Status排序作用的体现

image-20200426094333109

高级功能

当通过透视表生成了数据之后,便被保存在了数据帧中

查询指定的字段值的信息

image-20200426093516959

图形备忘录

本文标题:一文看懂pandas中的透视表

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

原始链接:http://www.renpeter.cn/2020/04/26/%E4%B8%80%E6%96%87%E7%9C%8B%E6%87%82pandas%E4%B8%AD%E7%9A%84%E9%80%8F%E8%A7%86%E8%A1%A8.html

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

Coffee or Tea