Pandas 更改多索引数据帧中列的分组

Pandas 更改多索引数据帧中列的分组,pandas,Pandas,假设存在一个数据帧: df = pd.DataFrame({ 'day': ['mon', 'mon', 'mon'], 'fruit': ['apple', 'apple', 'orange'], 'size': ['big', 'small', 'big'], 'price': [10, 11, 15], 'amount': [10, 10, 20] }).set_index('day') df = df.groupby(['day', 'fruit

假设存在一个数据帧:

df = pd.DataFrame({
    'day': ['mon', 'mon', 'mon'],
    'fruit': ['apple', 'apple', 'orange'],
    'size': ['big', 'small', 'big'],
    'price': [10, 11, 15],
    'amount': [10, 10, 20]
}).set_index('day')

df = df.groupby(['day', 'fruit', 'size'])['price', 'amount'].apply(lambda df: df.reset_index(drop=True)).unstack(level=[2])

                        price          amount
size             big    small    big    small
day fruit                   
mon apple   0   10.0     11.0   10.0     10.0
   orange   0   15.0      NaN   20.0      NaN

我想将列的顺序从price->big/small,amount->big/small更改为big->price/amount,small->price/amount。因此,预期的数据帧是:


                           big           small
size             price  amount   price  amount
day fruit                   
mon apple   0   10.0     10.0   11.0     10.0
   orange   0   15.0       20    Nan      NaN

实现这一点的方法是什么?

尝试
swaplevel
sort\u index

df_swap = df.swaplevel(0, 1, axis=1).sort_index(axis=1, ascending=[True,False])

Out[840]:
size           big        small
             price amount price amount
day fruit
mon apple  0  10.0   10.0  11.0   10.0
    orange 0  15.0   20.0   NaN    NaN