'Sorting columns of multiindex dataframe
I have a very large multi index dataframe with about 500 columns and each column has 2 sub columns.
The dataframe df
looks as:
B2 B5 B3
bkt A1 A2 A2 A1 Z2 C1
Date
2019-06-11 0.8 0.2 -6.0 -0.8 -4.1 -0.6
2019-06-12 0.8 0.2 -6.9 -1.6 -5.3 -1.2
df.columns
MultiIndex(levels=[['B2', 'B5', 'B3', .....], ['A1', 'A2' ......]],
labels=[[1, 1, ....], [1, 0, ....]],
names=[None, 'bkt'])
I am trying to sort only the column names and keep the values as it is within each column to get the following desired output:
B2 B3 B5
bkt A1 A2 C1 Z2 A1 A2
Date
2019-06-11 ..
2019-06-12 ..
..
represents the values from the original dataframe. I just didn't retype them.
Setup
df = pd.DataFrame([
[.8, .2, -6., -.8, -4.1, -.6],
[.8, .2, -6.9, -1.6, -5.3, -1.2]
],
pd.date_range('2019-06-11', periods=2, name='Date'),
pd.MultiIndex.from_arrays([
'B2 B2 B5 B5 B3 B3'.split(),
'A1 A2 A2 A1 Z2 C1'.split()
], names=[None, 'bkt'])
)
Solution 1:[1]
This should be done using sort_index
to move both the column names and data:
df.sort_index(axis=1, level=[0, 1], ascending=[True, False], inplace=True)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | cstoafer |