Set-up
I have a dataframe with amongst others a column with dates in string.
The date format is day/month/year, e.g. 05/12/2018.
The test_df dataframe looks like,
date_created
0 05/12/2018
1 04/12/2018
2 04/12/2018
3 03/12/2018
4 02/12/2018
5 30/11/2018
6 30/11/2018
7 30/11/2018
8 30/11/2018
9 29/11/2018
10 02/12/2018
11 29/11/2018
12 29/11/2018
Problem
I want this to be sorted on date, such that I have,
date_created
0 05/12/2018
1 04/12/2018
2 04/12/2018
3 03/12/2018
10 02/12/2018
4 02/12/2018
5 30/11/2018
6 30/11/2018
7 30/11/2018
8 30/11/2018
9 29/11/2018
11 29/11/2018
12 29/11/2018
but following this example,
test_df.sort_values(by='date_created', inplace=False, ascending=True)
gives,
date_created
4 02/12/2018
10 02/12/2018
3 03/12/2018
1 04/12/2018
2 04/12/2018
0 05/12/2018
9 29/11/2018
11 29/11/2018
12 29/11/2018
5 30/11/2018
6 30/11/2018
7 30/11/2018
8 30/11/2018
How do I reverse the order within the month?
The recommended solution is to convert your series to datetime, then sort:
df['date_created'] = pd.to_datetime(df['date_created'], dayfirst=True)
res = df.sort_values('date_created', ascending=False)
print(res)
date_created
0 2018-12-05
1 2018-12-04
2 2018-12-04
3 2018-12-03
4 2018-12-02
10 2018-12-02
5 2018-11-30
6 2018-11-30
7 2018-11-30
8 2018-11-30
9 2018-11-29
11 2018-11-29
12 2018-11-29
If you insist on keeping an object dtype series, you can then convert back to strings in a separate operation:
res['date_created'] = res['date_created'].dt.strftime('%d/%m/%Y')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With