How do I rearrange/reorder (not necessarily sort) a pandas dataframe index?
You can use loc
and give it a list of indices in the order that you want them:
df = pd.DataFrame({'A': [1, 2, 3, 4, 5, 6, 7],
'B': [0, 1, 0, 2, 1, 7, 1]},
index=['Sat', 'Tue', 'Sun', 'Fri',
'Wed', 'Mon', 'Thu'])
df = df.loc[['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], :]
df
# A B
# Sun 3 0
# Mon 6 7
# Tue 2 1
# Wed 5 1
# Thu 7 1
# Fri 4 2
# Sat 1 0
I've been struggling a bit with this myself and when you're working with MultiIndex Julien's suggestion becomes a little impractical. The solution, however, is relatively simple once you get used to it: simply reindex the dataframe with a new index. In your case this is really very easy:
days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri']
df2 = df.reindex(days)
df2
A B
Sun 3 0
Mon 6 7
Tue 2 1
Wed 5 1
Thu 7 1
Fri 4 2
Note that you cannot perform this operation in place.
But it's probably worth noting that you might have to create the index – you certainly do for a dataframe multiple indices. So be prepared to create the index properly using pd.Index()
or pd.MultiIndex()
When combined with df.swaplevel()
this gives you great flexibility.