-
数据透视表 百度百科
数据透视表(Pivot Table)是一种交互式的表,可以进行某些计算,如求和与计数等。所进行的计算与数据跟数据透视表中的排列有关。
之所以称为数据透视表,是因为可以动态地改变它们的版面布置,以便按照不同方式分析数据,也可以重新安排行号、列标和页字段。每一次改变版面布置时,数据透视表会立即按照新的布置重新计算数据。另外,如果原始数据发生更改,则可以更新数据透视表。 -
官方文档
pandas.pivot_table(data, values=None, index=None, columns=None, aggfunc='mean', fill_value=None, margins=False, dropna=True, margins_name='All', observed=False)
创建电子表格风格的透视表作为DataFrame。透视表里的级别会存储在结果DataFrame的索引和列上的多层索引对象(分层索引)中。
-
参数
参数 数据类型 意义 data DataFrame values column to aggregate, optional 聚合的列 index column, Grouper, array, or list of the previous 如果使Array,则长度需要与data相同;
list内可以包含除list之外的其他各种类型;
在透视表索引上分组的键,如果传入的是array,用法与列值一样columns column, Grouper, array, or list of the previous 如果传入array,长度需与data相同 aggfunc function, list of functions, dict, default numpy.mean 如果是list of functions,得到的透视表具有分层的列,他们的最高级别是函数名称;
如果是dict,key是需要聚合的列,value是函数或函数列fill_value scalar, default None 填充缺失值 margins boolean, default False 添加所有row/columns dropna boolean, default True 不包括全是NaN的列 margins_name string, default ‘All’ 当margins是True,包含总数的行/列名字 observed boolean, default False -
案例
>>> df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo", ... "bar", "bar", "bar", "bar"], ... "B": ["one", "one", "one", "two", "two", ... "one", "one", "two", "two"], ... "C": ["small", "large", "large", "small", ... "small", "large", "small", "small", ... "large"], ... "D": [1, 2, 2, 3, 3, 4, 5, 6, 7], ... "E": [2, 4, 5, 5, 6, 6, 8, 9, 9]}) >>> df A B C D E 0 foo one small 1 2 1 foo one large 2 4 2 foo one large 2 5 3 foo two small 3 5 4 foo two small 3 6 5 bar one large 4 6 6 bar one small 5 8 7 bar two small 6 9 8 bar two large 7 9 >>> table = pd.pivot_table(df, values='D', index=['A', 'B'], ... columns=['C'], aggfunc=np.sum) >>> table C large small A B bar one 4.0 5.0 two 7.0 6.0 foo one 4.0 1.0 two NaN 6.0
-
Reference
pandas.pivot_table()数据透视表详解
最新推荐文章于 2024-05-08 10:08:59 发布