Skip to content
Advertisement

how to sort pandas dataframe from one column

I have a data frame like this:

JavaScript

As you can see, months are not in calendar order. So I created a second column to get the month number corresponding to each month (1-12). From there, how can I sort this data frame according to calendar months’ order?

Advertisement

Answer

Use sort_values to sort the df by a specific column’s values:

JavaScript

If you want to sort by two columns, pass a list of column labels to sort_values with the column labels ordered according to sort priority. If you use df.sort_values(['2', '0']), the result would be sorted by column 2 then column 0. Granted, this does not really make sense for this example because each value in df['2'] is unique.

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