SunnyBoiz
SunnyBoiz

Reputation: 594

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

Any advice? Thank you!

Upvotes: 1

Views: 41

Answers (1)

jezrael
jezrael

Reputation: 862541

Specify format of datetimes in to_datetime and then 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

Upvotes: 2

Related Questions