以下情况目前在我当前的工作中经常出现。我有一个带有product-MultiIndex的熊猫DataFrame,如下所示:
cols = pd.MultiIndex.from_product([['foo1', 'foo2'], ['bar1', 'bar2']], names=['foo', 'bar'])
df = pd.DataFrame(np.arange(5*4).reshape(5, 4), index=range(5), columns=cols)
df
foo foo1 foo2
bar bar1 bar2 bar1 bar2
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
3 12 13 14 15
4 16 17 18 19
现在,我想交换DataFrame的列级别,所以我尝试了此操作:
df.reorder_levels(['bar', 'foo'], axis=1)
bar bar1 bar2 bar1 bar2
foo foo1 foo1 foo2 foo2
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
3 12 13 14 15
4 16 17 18 19
但这不是我想要的。我想根据这个很好的规范产品排序来更改列的顺序。我当前的解决方法如下:
cols_swapped = pd.MultiIndex.from_product([['bar1', 'bar2'], ['foo1', 'foo2']], names=['bar', 'foo'])
df.reorder_levels(cols_swapped.names, axis=1).loc[:, cols_swapped])
bar bar1 bar2
foo foo1 foo2 foo1 foo2
0 0 2 1 3
1 4 6 5 7
2 8 10 9 11
3 12 14 13 15
4 16 18 17 19
这可以,但是效果不是很好,例如因为它更加令人困惑,因此必须创建一个新的MultiIndex。我经常遇到这种情况,就是我为所有列计算了一个新功能。但是在将concat
赋予我的df
之后,它想将相应的新关卡“分类”到一个新位置。假设新功能位于第0级,那么解决方法如下:
new_order = [1, 2, 0, 3, 4]
cols_swapped = pd.MultiIndex.from_product(
[df.columns.levels[i] for i in new_order],
names = [df.columns.names[i] for i in new_order]
)
df_swap = df.reorder_levels(cols_swapped.names, axis=1).loc[:, cols_swapped]
这还真不错。
熊猫支持吗?如果是的话,哪种方法更优雅?
答案 0 :(得分:1)
我认为需要swaplevel
和sort_index
:
df = df.swaplevel(0,1, axis=1).sort_index(axis=1)
print (df)
bar bar1 bar2
foo foo1 foo2 foo1 foo2
0 0 2 1 3
1 4 6 5 7
2 8 10 9 11
3 12 14 13 15
4 16 18 17 19