3

I have a pandas data frame I want to reorder the index using a specific order.

from random import randint
import pandas as pd
days = ["Tuesday", "Thursday", "Monday", "Wednesday"]
df = pd.DataFrame({"Value": [randint(0, 9) for i in range(len(days)*2)]}, 
                  index=[day for day in days for i in range(2)])
myorder = ["Monday", "Tuesday", "Wednesday", "Thursday"]

The specific order is as notified by the list myorder

2 Answers 2

2

Use CategoricalIndex + sort_index:

df.index = pd.CategoricalIndex(df.index, categories=myorder, ordered=True)
df = df.sort_index()
print (df)
           Value
Monday         3
Monday         3
Tuesday        4
Tuesday        3
Wednesday      3
Wednesday      4
Thursday       5
Thursday       2
Sign up to request clarification or add additional context in comments.

Comments

1

This is one method, if you wish to avoid categoricals:

orderdic = dict(zip(myorder, range(len(myorder))))

df = df.assign(order=df.index.to_series().map(orderdic))\
       .sort_values('order').drop('order', 1)

#            Value
# Monday         6
# Monday         6
# Tuesday        9
# Tuesday        1
# Wednesday      1
# Wednesday      3
# Thursday       0
# Thursday       7

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.