Reindex columns after using crosstab with regular month order instead of alphabetic

Viewed 190

I have the following output after use crosstab, see image attached:

enter image description here

My question is the following: How can I sort the columns by month based on year position instead of by alphabetical order?

2 Answers
from calendar import month_abbr

df.reindex(columns=month_abbr[1:])

In the built-in calendar module, there is month_abbr that gives abbreviation of the months. Its length, however, is 13 as it includes an empty string at index 0 (to ease the regular indexing like 3 is for March etc.). In short, you can use it to re-index your data frame over columns.

If you want to stick with pandas just create a yearly date_range with month frequency then strftime to get the abbreviations.

import pandas as pd

cols = pd.date_range('2010-01-01', '2010-12-31', freq='MS').strftime('%b')
#Index(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 
#       'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']),

df = df.reindex(cols, axis=1)
Related