I have python pandas dataframe, in which a column contains month name.
How can I do a custom sort using a dictionary, for example:
custom_dict = {'March':0, 'April':1, 'Dec':3}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Pandas 0.15 introduced Categorical Series, which allows a much clearer way to do this:
First make the month column a categorical and specify the ordering to use.
Now, when you sort the month column it will sort with respect to that list:
Note: if a value is not in the list it will be converted to NaN.
An older answer for those interested…
You could create an intermediary series, and
set_indexon that:As commented, in newer pandas, Series has a
replacemethod to do this more elegantly:The slight difference is that this won’t raise if there is a value outside of the dictionary (it’ll just stay the same).