Issue
I have the following dataframe:
What is the best way to maintain the ordering of level2 (Checks, Check Avg, Checks, Check AVg etc..), but sort the dates of the parent level in ascending order?
Solution
Add sort_remaining=False
to sort_index
to prevent sorting levels below specified:
df = df.sort_index(level=0, axis=1, sort_remaining=False)
df
:
Week 2021-10-11 2021-10-18 2021-10-25
Checks Check Avg Checks Check Avg Checks Check Avg
11th Street 4 5 2 3 0 1
16th Street 10 11 8 9 6 7
Bala Cynwyd 16 17 14 15 12 13
Sample Data Used:
import numpy as np
import pandas as pd
df = pd.DataFrame(
np.arange(18).reshape((-1, 6)),
index=['11th Street', '16th Street', 'Bala Cynwyd'],
columns=pd.MultiIndex.from_arrays(
[np.repeat(pd.to_datetime(['2021-10-25', '2021-10-18', '2021-10-11']),
2),
['Checks', 'Check Avg'] * 3],
names=['Week', None]
)
)
df
:
Week 2021-10-25 2021-10-18 2021-10-11
Checks Check Avg Checks Check Avg Checks Check Avg
11th Street 0 1 2 3 4 5
16th Street 6 7 8 9 10 11
Bala Cynwyd 12 13 14 15 16 17
Answered By - Henry Ecker
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.