Skip to content Skip to sidebar Skip to footer

Sort Pandas Dataframe Of Month Names In Correct Order

I have a dataframe with names of months of the year, I.e. Jan, Feb, March etc and I want to sort the data first by month, then by category so it looks like Month_Name | Cat Jan

Solution 1:

pandas doesn't do custom sort functions for you, but you can easily add a temporary column which is the index of the month, and then sort by that

months = {datetime.datetime(2000,i,1).strftime("%b"): i for i in range(1, 13)}
df["month_number"] = df["month_name"].map(months)
df.sort(columns=[...])

You may wish to take advantage of pandas' good date parsing when reading in your dataframe, though: if you store the dates as dates instead of string month names then you'll be able to sort natively by them.

Solution 2:

Use Sort_Dataframeby_MonthandNumeric_cols function to sort dataframe by month and numeric column:

You need to install two packages are shown below.

pip install sorted-months-weekdays
pip install sort-dataframeby-monthorweek

Example:

import pandas as pd

from sorted_months_weekdays import *

from sort_dataframeby_monthorweek import *

df = pd.DataFrame([['Jan',23],['Jan',16],['Dec',35],['Apr',79],['Mar',53],['Mar',12],['Feb',3]], columns=['Month','Sum'])
df
Out[11]: 
  MonthSum0Jan231Jan162Dec353Apr794Mar535Mar126Feb3

To get sorted dataframe by month and numeric column I have used above function.

Sort_Dataframeby_MonthandNumeric_cols(df = df, monthcolumn='Month',numericcolumn='Sum')
Out[12]: 
  Month  Sum
0   Jan   161   Jan   232   Feb    33   Mar   124   Mar   535   Apr   796Dec35

Post a Comment for "Sort Pandas Dataframe Of Month Names In Correct Order"