如何删除熊猫数据透视表中的多级索引

Posted

技术标签:

【中文标题】如何删除熊猫数据透视表中的多级索引【英文标题】:How to remove multilevel index in pandas pivot table 【发布时间】:2017-11-14 18:13:17 【问题描述】:

我有一个给定的数据框:

df = 'TYPE' : pd.Series(['Advisory','Advisory1','Advisory2','Advisory3']),
 'CNTRY' : pd.Series(['IND','FRN','IND','FRN']),
 'VALUE' : pd.Series([1., 2., 3., 4.])
df = pd.DataFrame(df)
df = pd.pivot_table(df,index=["CNTRY"],columns=["TYPE"]).reset_index()

旋转后,如何使具有列和df 的数据框如下所示;删除多级索引,VALUE

Type|CNTRY|Advisory|Advisory1|Advisory2|Advisory3
0     FRN     NaN      2.0      NaN     4.0 
1     IND     1.0      NaN      3.0     NaN 

【问题讨论】:

【参考方案1】:

您可以添加参数values

df = pd.pivot_table(df,index="CNTRY",columns="TYPE", values='VALUE').reset_index()
print (df)
TYPE CNTRY  Advisory  Advisory1  Advisory2  Advisory3
0      FRN       NaN        2.0        NaN        4.0
1      IND       1.0        NaN        3.0        NaN

对于删除列名rename_axis:

df = pd.pivot_table(df,index="CNTRY",columns="TYPE", values='VALUE') \
       .reset_index().rename_axis(None, axis=1)
print (df)
  CNTRY  Advisory  Advisory1  Advisory2  Advisory3
0   FRN       NaN        2.0        NaN        4.0
1   IND       1.0        NaN        3.0        NaN

但也许只有pivot

df = df.pivot(index="CNTRY",columns="TYPE", values='VALUE') \
       .reset_index().rename_axis(None, axis=1)
print (df)
  CNTRY  Advisory  Advisory1  Advisory2  Advisory3
0   FRN       NaN        2.0        NaN        4.0
1   IND       1.0        NaN        3.0        NaN

因为pivot_table默认聚合重复聚合函数mean

df = 'TYPE' : pd.Series(['Advisory','Advisory1','Advisory2','Advisory1']),
 'CNTRY' : pd.Series(['IND','FRN','IND','FRN']),
 'VALUE' : pd.Series([1., 4., 3., 4.])
df = pd.DataFrame(df)
print (df)
  CNTRY       TYPE  VALUE
0   IND   Advisory    1.0
1   FRN  Advisory1    1.0 <-same FRN and Advisory1 
2   IND  Advisory2    3.0
3   FRN  Advisory1    4.0 <-same FRN and Advisory1 

df = df.pivot_table(index="CNTRY",columns="TYPE", values='VALUE')
       .reset_index().rename_axis(None, axis=1)
print (df)
TYPE   Advisory  Advisory1  Advisory2
CNTRY                                
FRN         0.0        2.5        0.0
IND         1.0        0.0        3.0

替代groupby、聚合函数和unstack

df = df.groupby(["CNTRY","TYPE"])['VALUE'].mean().unstack(fill_value=0)
      .reset_index().rename_axis(None, axis=1)
print (df)
  CNTRY  Advisory  Advisory1  Advisory2
0   FRN       0.0        2.5        0.0
1   IND       1.0        0.0        3.0

【讨论】:

【参考方案2】:

您可以将set_indexunstack 一起使用

df.set_index(['CNTRY', 'TYPE']).VALUE.unstack().reset_index()

TYPE CNTRY  Advisory  Advisory1  Advisory2  Advisory3
0      FRN       NaN        2.0        NaN        4.0
1      IND       1.0        NaN        3.0        NaN

【讨论】:

以上是关于如何删除熊猫数据透视表中的多级索引的主要内容,如果未能解决你的问题,请参考以下文章

如何组合熊猫数据透视表中的列?

如何合并熊猫数据透视表中的多索引层?

熊猫数据透视表中的小计

熊猫:从数据透视表中的另一列中减去一列

如何删除透视表中的很多汇总行

为熊猫数据透视表中的每个值列定义 aggfunc