简体   繁体   中英

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

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

在此处输入图像描述

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM