[英]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.