以下情况目前在我目前的工作中经常出现。我有一个带有产品多索引的 pandas 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
这可行,但不太好,例如因为它更令人困惑并且必须创建一个新的多索引。我经常遇到这种情况,是我为所有列计算一个新特征。但是在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]
这更不好。
pandas 支持这个吗?如果是,更优雅的方法是什么?
最佳答案
我相信需要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
关于python - 重新排序 pandas from_product-MultiIndex DataFrame 中的级别以及值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51242015/