简体   繁体   English

如何使用对应的列值对多索引列名进行排序?

[英]How to sort multiindex column names with their corresponding column values?

I have a table like the image我有一张像图片一样的桌子在此处输入图片说明

I want to sort the second column names of multiindex but the columns must keep their corresponding column values.我想第二列名排序, multiindex ,但列必须保持其相应的列值。

So I tried this code:所以我尝试了这个代码:

df.columns=df.sort_index(axis=1,level=[1],ascending=[True]).columns

But is sorting only the names of the columns, and the columns are changing the data.但是只对列的名称进行排序,而列正在更改数据。

How can I sort the name of the columns without changing their corresponding data?如何在不更改相应数据的情况下对列的名称进行排序?

Thanks in advance提前致谢

Sample DataFrame:示例数据帧:

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

Modifying columns will overwrite the columns and not affect the values:修改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

*Notice no values have changed even though the columns have been. *请注意,即使列已更改,值也未更改。


To actually sort the DataFrame based on values, overwrite the DataFrame with the return from sort_index :要根据值对 DataFrame 进行实际排序,请使用 sort_index 的返回值覆盖sort_index

df = df.sort_index(axis=1, level=1, ascending=True)

Or inplace :inplace

df.sort_index(axis=1, level=1, ascending=True, inplace=True)

df : 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

It's interesting that in my search for duplicates the first and closest result I could find is Sorting columns of multiindex dataframe which has an answer very similar to OP's attempt.有趣的是,在我搜索重复项时,我能找到的第一个也是最接近的结果是Sorting columns of multiindex dataframe ,其答案与 OP 的尝试非常相似。 But in that question the goal was to "sort only the column names and keep the values as it is within each column" which does not sort the DataFrame values but only modifies the DataFrame cosmetically.但是在那个问题中,目标是“仅对列名进行排序并保持每列中的值不变”,这不会对 DataFrame 值进行排序,而只是在外观上修改 DataFrame。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM