Search code examples
pythonpandasdataframecrosstab

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


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?


Solution

  • 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.