简体   繁体   中英

Python How to sort multi index Columns in Dataframe at different levels?

I am trying to sort the multi index columns at level 1 of a dataframe df

            |05/12/2020                 |05/13/2020
Created By  |Accuracy   Achieved %      |Accuracy   Achieved %
------------------------------------------------------------------
John        |  90        105            |   85       105

I want to sort the columns in level 1 as Achieved % & Accuracy instead of Accuracy and Achieved %

Is there a way to do it?

Found the answer:)

Used sort_index

pivot = pivot.sort_index(level=1, axis=1, sort_remaining=False, ascending=False) pivot = pivot.sort_index(level=0, axis=1, sort_remaining=False, ascending=True)

Doc: https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.DataFrame.sortlevel.html

Thanks

Assuming that your DataFrame is in df , you can do it with the following single instruction:

df = df.reindex(columns=df.columns.sortlevel([0, 1],ascending=[True, False])[0])

You can specify sort levels and order (for the levels given), passing lists as respective parameters.

The trailing [0] is needed, because sortlevel returns a tuple (sorted_index, indexer) , but we need only the sorted index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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