pivot_table可以实现Excel数据透视表的功能,但是经过pivot_table函数处理后的dataframe的列是多层索引,需要转化成单层索引,具体步骤如下:
1、使用pivot_table函数,建立数据透视表
df_1为数据源,包含5列,amount列为数值列,用于聚合;
创建数据透视表,index=['group_series', 'buy_no'],columns=['xmonth'],NA值用0填充,结果如下:

df_1_out=pd.pivot_table(df_1, index=['group_series', 'buy_no'], columns=['xmonth'], values=['amount'], aggfunc='sum', fill_value=0)
df_1_out

2、列索引处理
# 查看列索引
df_1_out.columns

# 查看一级列索引
df_1_out.columns.levels[0]
# 查看二级列索引
df_1_out.columns.levels[1]
# 过滤一级列索引
df_1_out.columns=df_1_out.columns.droplevel(level=0)



3、行索引处理
# 查看行索引
df_1_out.index

# 重置行索引
df_1_out.reset_index(inplace=True)
df_1_out.index

最终数据结果如下:

pivot_table()简介:
DataFrame.pivot_table(values=None, index=None, columns=None, aggfunc='mean', fill_value=None, margins=False, dropna=True, margins_name='All')
values:要聚合的列或列的列表
index:数据透视的index,从原始数据的列中筛选
columns:数据透视表的columns,从原始数据的列中筛选
aggfunc:用于聚合的函数,默认为numpy,mean,支持numpy计算方法
fill_value:填充NA值,默认不填充
margins:添加行列的总计,默认不显示
dropna:如果整行都为NA值,则进行丢弃,默认丢弃
margins_name:在margins参数为true时,用来修改margins的名称
网友评论