Python Pandas多索引值不会在数据透视表中移动

时间:2014-08-12 22:40:58

标签: python pandas pivot-table

我有以下Python Pandas数据帧:

enter image description here

将pandas导入为pd

然后我运行此代码来格式化表格我想要的:

col_mapping = {'Central Mixedwood (CM)': ['CM Area (ha)', 'CM % of LSA*'], 
               'Lower Boreal Highlands (LBH)': ['LBH Area (ha)','LBH % of LSA'], 
                'Total LSA': ['Total Area (ha)', 'Total Area % of LSA']}
cols = [(k,v) for k,sublist in col_mapping.items() 
              for v in sublist]
p_table.columns = pd.MultiIndex.from_tuples(cols)
p_table

哪个收益率: enter image description here

标签都在正确的位置,但值没有转移到正确的列,它们保持与以前相同,我该如何解决?

1 个答案:

答案 0 :(得分:1)

您需要先重新索引轴:

>>> idx = pd.MultiIndex.from_tuples(cols)
>>> p_table = p_table.reindex_axis(idx.get_level_values(1), axis=1)
>>> p_table.columns = idx