问题场景:
pd.pivot_table是pandas的数据透视表功能,在对多维度数据进行统计计算时,非常好用。
但在我个人使用过程中遇到过一个问题:
当横向按照“1个及以上维度+多个量值”或“2个及以上维度”进行展开时,列名称存在多维。
import numpy as np
import pandas as pd
df=pd.DataFrame({'where':['上海','上海','上海','北京','北京','北京'],
'what':['西瓜','香蕉','苹果','西瓜','香蕉','苹果'],
'how much':[1,2,3,1.1,2.1,3.1],
'how many':[10,20,30,11,21,31]})
df
![8dbc74c58e5f43ad10beaa2eba39c104.png](https://i-blog.csdnimg.cn/blog_migrate/50eed08e6f32fb3e05000077fea66dd6.png)
df_pt=pd.pivot_table(df,index=["where"]#纵向展开维度
,columns=["what"]#横向展开维度
,values=["how much","how many"],#量值
aggfunc={'how much':np.mean
,'how many':np.sum
},fill_value=0)
df_pt
![2e663cbf0cf18eafbdd1089769f1c0b5.png](https://i-blog.csdnimg.cn/blog_migrate/4e62b65fcbfdac2c30d4e85f7995dc52.png)
后续引用列时,需要多维引用方式:
![7e46d6ce233bb54d95044586e213a959.png](https://i-blog.csdnimg.cn/blog_migrate/6141ffcadc55bb038655d1133befe7a6.png)
问:如果快捷的将列名称替换为扁平化1维的名称?
解决方案:
#列名称扁平
#初始化空list用于接收
rename_the_df=[]
#遍历原多维列名称
for x in df_pt.columns:
rename_the_df.append("_".join(x))
#赋值
df_pt.columns=rename_the_df
df_pt.reset_index(inplace=True)
df_pt
效果演示:
![4d4367387a3328cb06295e30c0359d08.png](https://i-blog.csdnimg.cn/blog_migrate/68a5c73920764e97fb7b262735d5489f.jpeg)