[英]How to sort multiindex column names with their corresponding column values?
示例数据帧:
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 的返回值覆盖sort_index
:
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。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.