具有多索引列的熊猫数据框-更改级别

时间:2020-06-01 04:00:51

标签: python pandas multi-index levels

源数据:

enter image description here

pd.pivot_table(ceshi, values=['num1', 'num2'], index=['date'],
            columns=['c'], aggfunc={'num1': np.sum,'num2': np.sum}, fill_value=0)

enter image description here

如何转变为?:

enter image description here

1 个答案:

答案 0 :(得分:0)

DataFrame.swaplevelDataFrame.sort_index一起使用:

df = pd.pivot_table(ceshi, values=['num1', 'num2'], index=['date'],
                   columns=['c'], aggfunc={'num1': np.sum,'num2': np.sum}, fill_value=0)

然后:

df = df.swaplevel(1,0, axis=1).sort_index(axis=1)