简体   繁体   English

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

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

I have the following output after use crosstab, see image attached:使用交叉表后,我有以下 output,见附图:

在此处输入图像描述

My question is the following: How can I sort the columns by month based on year position instead of by alphabetical order?我的问题如下:如何根据年份 position 而不是按字母顺序对列进行排序?

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.在内置的calendar模块中, month_abbr给出了月份的缩写。 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.).然而,它的长度是 13,因为它在索引 0 处包含一个空字符串(以简化常规索引,如 3 用于 March 等)。 In short, you can use it to re-index your data frame over columns .简而言之,您可以使用它在columns上重新索引您的数据框。

If you want to stick with pandas just create a yearly date_range with month frequency then strftime to get the abbreviations.如果你想坚持使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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