Jgallagher
Jgallagher

Reputation: 111

Sorting a column by date

I am trying to sort this 'Month' column within my 'Mon18' table to run from January through to December with its corresponding count. When I try sort the column it orders it either by highest count or by sorting the 'Month' Column alphabetically. See an example below:

print (df)
            Months  Count
10      April 2018    684
3      August 2018   1098
1    December 2018   1207
11   February 2018    642
8     January 2018    847
5        July 2018   1040
6        June 2018    986
9       March 2018    809
7         May 2018    854
0    November 2018   1215
2     October 2018   1128
4   September 2018   1062

Upvotes: 1

Views: 44

Answers (1)

jezrael
jezrael

Reputation: 862511

Idea is convert column to datetimes and use Series.argsort for indices passed to DataFrame.iloc:

df = df.iloc[pd.to_datetime(df['Months'], format='%B %Y').argsort()]
print (df)
            Months  Count
8     January 2018    847
11   February 2018    642
9       March 2018    809
10      April 2018    684
7         May 2018    854
6        June 2018    986
5        July 2018   1040
3      August 2018   1098
4   September 2018   1062
2     October 2018   1128
0    November 2018   1215
1    December 2018   1207

Upvotes: 1

Related Questions