使用具有常规月份顺序而不是字母顺序的交叉表后重新索引列

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

使用交叉表后我有以下输出,见附图:

我的问题如下:如何根据年份而不是字母顺序按月对列进行排序?

from calendar import month_abbr

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

在给出月份缩写的内置calendar module, there is month_abbr中。然而,它的长度是 13,因为它在索引 0 处包含一个空字符串(以简化常规索引,例如 3 代表 March 等)。简而言之,您可以使用它在 columns.

上重新索引您的数据框

如果你想坚持使用 pandas,只需创建一个每年 date_range 的月份频率,然后 strftime 获取缩写。

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)