2

I have the following dataframe :

        month       price
0       April  102.478015
1      August   94.868053
2    December   97.278205
3    February  100.114510
4     January   99.419109
5        July   93.402928
6        June   96.114224
7       March  101.297762
8         May  102.905340
9    November   97.952169
10    October   95.606478
11  September   94.226803

I would like to have the months in a coherent order (January in the first row until December in the 12th row). How please could I do ?

If necessary, you can copy this dataframe and then execute

pd.read_clipboard(sep='\s\s+')

to have the dataframe on your jupyter notebook

1 Answer 1

3

Convert values to ordered categoricals, so possible use DataFrame.sort_values:

cats = ['January','February','March','April','May','June',
        'July','August','September','October','November','December']
df['month'] = pd.CategoricalIndex(df['month'], ordered=True, categories=cats)
#alternative
#df['month'] = pd.Categorical(df['month'], ordered=True, categories=cats)
df = df.sort_values('month')
print (df)
        month       price
4     January   99.419109
3    February  100.114510
7       March  101.297762
0       April  102.478015
8         May  102.905340
6        June   96.114224
5        July   93.402928
1      August   94.868053
11  September   94.226803
10    October   95.606478
9    November   97.952169
2    December   97.278205
Sign up to request clarification or add additional context in comments.

3 Comments

and you can use calendar.month_name to generate cats variable
Why pd.CategoricalIndex instead of pd.Categorical @jez?
@yatu - Because in some oldier pandas version Categorical failed, only working CategoricalIndex

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.