John
John

Reputation: 1465

Reorder Columns Based on a Dictionary

I have a DataFrame that looks like

Day    Oct    Dec    Nov
1       5      7      3
2       0      23     8
3       2      12     10

with ~30 records.

Unfortunately, I don't always know what the columns are going to be (it is generated from a live dataset for different months). I know they will be in the set (Jan, Feb, Mar, Apr...Dec) and that there will be three columns, but I don't know which three and I don't know what order.

How can I force them to be in the appropriate calendar order?

I assume I need to sort them as integers somehow by linking the names to a dictionary like

month_dict = {'Jan': 0, 
          'Feb': 1, 
          'Mar': 2, 
          'Apr': 3, 
          'May': 4, 
          'Jun': 5, 
          'Jul': 6,
          'Aug': 7, 
          'Sep': 8, 
          'Oct': 9, 
          'Nov': 10, 
          'Dec': 11}

but I can't figure out how to use that to sort the columns

Upvotes: 1

Views: 790

Answers (1)

Stefan
Stefan

Reputation: 42905

There is:

df = df.rename(columns=month_dict).sort_index(axis=1)

Upvotes: 2

Related Questions