Sorting a dataset by month with month column as an object

Question:

I’m trying to sort my data by "Month" (which is an object and I can’t convert it to datetime for some reason), but nothing happens when using .sort_values. No error is printed either. I have three months in my current dataset, "Jul", "Aug", and "Sep" (other datasets might have other months)

I have tried the following snippet of code, which I would have expected to work:

List_Of_Months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

Test_LM_Cboe.sort_values(by=['Month'], key=lambda x : pd.Categorical(x, categories=List_Of_Months, ordered=True))

I would have expected Jul to be shown first, then Aug and lastly Sep. However, nothing has changed in the dataset, it’s the exact same as before:

wrong sort data

I ultimately want to sort the month column so as to make a pivot table where the months comes in the right order.

Asked By: Marc225

||

Answers:

I think here is what you looking for …

List_Of_Months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]#your list

keys_of_months = [i for i in range(1,13)] #keys for sorting

dict_of_months = dict(zip(List_Of_Months,keys_of_months)) #list to dict

Test_LM_Cboe.sort_values(by=['Month'], key=lambda x: x.map(dict_of_months)) #applying on the dataframe
  
Answered By: Amin Samani
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.