pandas使用教程:数据透视表函数 pivot_table

导入数据

使用pandas官方教程提供的示例数据,导入地址:
http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html

import pandas as pd

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

参数说明

pandas.pivot_table(data, values=None, index=None, columns=None, aggfunc=‘mean’, fill_value=None, margins=False, dropna=True, margins_name=‘All’, observed=False, sort=True)

主要参数:

  • data:待操作的 DataFrame
  • values:被聚合操作的列,可选项
  • index:行分组键,作为结果 DataFrame 的行索引
  • columns:列分组键,作为结果 DataFrame 的列索引
  • aggfunc:聚合函数/函数列表,默认 numpy.mean ,这里要注意如果 aggfunc 中存在函数列表,则返回的 DataFrame 中会显示函数名称
  • fill_value:默认 None,可设定缺省值
  • dropna:默认 True,如果列的所有值都是 NaN,将被删除;False 则保留
  • margins:默认 False,设置为 True 可以添加行/列的总计
  • margins_name:默认显示 ‘ALL’,当 margins = True 时,可以设定 margins 行/列的名称

常用操作

指定index进行聚合

使用pivot_table时必须要指定index,因为计算时要根据index进行聚合。

import numpy as np
pd.pivot_table(df,
               index='A',
               aggfunc=[np.sum])

	sum
	D	E
A		
bar	22	32
foo	11	22
通过指定value来选择被聚合的列
import numpy as np
pd.pivot_table(df,
               values='D',
               index='A',
               aggfunc=[np.count_nonzero])

count_nonzero
	D
A	
bar	4
foo	5

当只指定index进行聚合时,其实用groupby可以实现同样的效果。

df.groupby(['A'])['D'].count().reset_index()

	A	D
0	bar	4
1	foo	5
添加columns参数,对列分组
pd.pivot_table(df.head(10),
               values='D',
               index='A',
               columns='B',
               aggfunc=np.count_nonzero)
C	large	small
A		
bar	2	2
foo	2	3
对于上面结果中的空值,使用fill_value参数统一填充为0
pd.pivot_table(df.head(10),
               values='D',
               index='A',
               columns='B',
               fill_value=0,
               aggfunc=np.count_nonzero)

注意此时的aggfunc参数,当参数值包含列表时,在结果DataFrame中就会显示函数名称。

添加合计列

如果需要添加合计列,只需指定margins=True即可,同时根据需要指定合计名称。

pd.pivot_table(df.head(10),
               values='D',
               index='A',
               columns='B',
               fill_value=0,
               margins=True,
               aggfunc=np.count_nonzero)
B	one	two	All
A			
bar	2	2	4
foo	3	2	5
All	5	4	9
pd.pivot_table(df,
               values='D',
               index=['A','B'],
               columns=['C'],
               fill_value=0,
               margins=True,
               aggfunc=np.count_nonzero)
C	large	small	All
A	B			
bar	one	1	1	2
	two	1	1	2
foo	one	2	1	3
	two	0	2	2
All		4	5	9
指定合计名称
pd.pivot_table(df.head(10),
               values='D',
               index=['A','B'],
               columns=['C'],
               fill_value=0,
               margins=True,
               margins_name='合计',
               aggfunc=[np.count_nonzero])
	count_nonzero
C	large	small	合计
A	B			
bar	one	1	1	2
	two	1	1	2
foo	one	2	1	3
	two	0	2	2
合计		4	5	9

当然与groupby类似,对于计算函数我们可以同时指定多种方式。

pd.pivot_table(df,
               values='D',
               index=['A'],
               columns=['C'],
               fill_value=0,
               margins=True,
               aggfunc=[max,sum,np.count_nonzero])
	max					sum					count_nonzero
C	large	small	All	large	small	All	large	small	All
A									
bar	7	6	7	11	11	22	2	2	4
foo	2	3	3	4	7	11	2	3	5
All	7	6	7	15	18	33	4	5	9

猜你喜欢

转载自blog.csdn.net/weixin_46530492/article/details/131638248