简体   繁体   English

按升序对列进行排序

[英]Sorting Columns By Ascending Order

Given this example dataframe, 给定这个示例数据框,

Date    01012019   01022019    02012019    02022019    03012019    03022019
Period
1         45          21           43         23           32          23
2         42          12           43         11           14          65
3         11          43           24         23           21          12

I will like to sort the date based on the month - (the date is in ddmmyyyy). 我想根据月份对日期进行排序-(日期在ddmmyyyy中)。 However, the date is a string when I type(date). 但是,当我键入(日期)时,日期是一个字符串。 I tried to use pd.to_datetime but it failed with an error month must be in 1..12. 我尝试使用pd.to_datetime,但是它失败了,并且错误月份必须在1..12中。

Any advice? 有什么建议吗? Thank you! 谢谢!

Specify format of datetimes in to_datetime and then sort_index : 指定日期时间的格式to_datetime然后sort_index

df.columns = pd.to_datetime(df.columns, format='%d%m%Y')
df = df.sort_index(axis=1)
print (df)
      2019-01-01  2019-01-02  2019-01-03  2019-02-01  2019-02-02  2019-02-03
Date                                                                        
1             45          43          32          21          23          23
2             42          43          14          12          11          65
3             11          24          21          43          23          12

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

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