我有一个多索引数据框,我不想按字母顺序(axis=1)排序列,而是按自定义顺序排序。 我使用unstack将df转换为多索引,并使用sort\u index进行排序:
df = df.unstack().swaplevel(1,0, axis=1).sort_index(axis=1, level=0)
我想我的指标列将排序,我希望,而不是按字母表,例如:metric2,metric3,metric1在椅子索引和表索引(和更多)
dim3 chair table
metric1 metric2 metric3 metric1 metric2 metric3
dim1 dim2
a day1 1.0 10.0 123.0 NaN NaN NaN
b day2 NaN NaN NaN 2.0 20.0 456.0
请不要介意空值,这只是一个例子
适应大熊猫
现在检查一下
根据您的喜好重新排列并使用
.loc
这种方法应该给你最大限度的控制
将此方法与您的数据帧相适应,如下所示:
相关问题 更多 >
编程相关推荐