示例数据帧:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.arange(1, 17).reshape(-1, 4),
columns=pd.MultiIndex.from_product([['a', 'b'], ['d', 'c']]))
a b
d c d c
0 1 2 3 4
1 5 6 7 8
2 9 10 11 12
3 13 14 15 16
修改columns 将覆盖列而不影响值:
df.columns = ['w', 'x', 'y', 'z']
w x y z
0 1 2 3 4
1 5 6 7 8
2 9 10 11 12
3 13 14 15 16
*请注意,即使列发生了变化,也没有任何值发生变化。
要实际根据值对 DataFrame 进行排序,请使用 sort_index 的返回值覆盖 DataFrame:
df = df.sort_index(axis=1, level=1, ascending=True)
或inplace:
df.sort_index(axis=1, level=1, ascending=True, inplace=True)
df:
a b a b
c c d d
0 2 4 1 3
1 6 8 5 7
2 10 12 9 11
3 14 16 13 15
有趣的是,在我搜索重复项时,我能找到的第一个也是最接近的结果是 Sorting columns of multiindex dataframe,它的答案与 OP 的尝试非常相似。但在那个问题中,目标是“仅对列名进行排序,并保持每列中的值不变”,这不对 DataFrame 值进行排序,而只是从外观上修改 DataFrame。