Skip to content
Advertisement

Sort a pandas dataframe series by month name

I have a Series object that has:

JavaScript

Problem statement: I want to make it appear by month and compute the mean price for each month and present it with a sorted manner by month.

Desired Output:

JavaScript

I thought of making a list and passing it in a sort function:

JavaScript

but the sort_values doesn’t support that for series.

One big problem I have is that even though

df = df.sort_values(by='date',ascending=True,inplace=True) works to the initial df but after I did a groupby, it didn’t maintain the order coming out from the sorted df.

To conclude, I needed from the initial data frame these two columns. Sorted the datetime column and through a groupby using the month (dt.strftime(‘%B’)) the sorting got messed up. Now I have to sort it by month name.


My code:

JavaScript

Advertisement

Answer

Thanks @Brad Solomon for offering a faster way to capitalize string!

Note 1 @Brad Solomon’s answer using pd.categorical should save your resources more than my answer. He showed how to assign order to your categorical data. You should not miss it :P

Alternatively, you can use.

JavaScript

Note 2 groupby by default will sort group keys for you. Be aware to use the same key to sort and groupby in the df = df.sort_values(by=SAME_KEY) and total = (df.groupby(df[SAME_KEY])['Price'].mean()). Otherwise, one may gets unintended behavior. See Groupby preserve order among groups? In which way? for more information.

Note 3 A more computationally efficient way is first compute mean and then do sorting on months. In this way, you only need to sort on 12 items rather than the whole df. It will reduce the computational cost if one don’t need df to be sorted.

Note 4 For people already have month as index, and wonder how to make it categorical, take a look at pandas.CategoricalIndex @jezrael has a working example on making categorical index ordered in Pandas series sort by month index

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement