-2

I have a df with dates in the format %B %Y (e.g. June 2021, December 2022 etc.)

Date Price
Apr 2022 2
Dec 2021 8

I am trying to sort dates in order of oldest to newest but when I try:

.sort_values(by='Date', ascending=False)

it is ordering in alphabetical order.

The 'Date' column is an Object.

flaws49
  • 29
  • 6
  • Does this answer your question? [Convert Column to Date Format (Pandas Dataframe)](https://stackoverflow.com/questions/28161356/convert-column-to-date-format-pandas-dataframe) Your problem is the same as in this linked question - you need to convert your column from object to date or datetime. – Lomtrur May 06 '22 at 11:46
  • `ascending=False` will result in sorting newest to oldest, not oldest to newest – Stef May 06 '22 at 12:54
  • Try `df.sort_values('Date', key=pd.to_datetime)` – Stef May 06 '22 at 12:55
  • @Stef feel free to add an answer, ill upvote :) – Sash Sinha May 06 '22 at 13:15
  • Oh, it looks like someone had posted an answer, but then deleted it. – Stef May 06 '22 at 14:00

1 Answers1

0
  • ascending=False will sort from newest to oldest, but you are asking to sort oldest to newest, so you don't need that option;
  • there is a key option to specify how to parse the values before sorting them;
  • you may or may not want option ignore_index=True, which I included below.

We can use the key option to parse the values into datetime objects with pandas.to_datetime.

import pandas as pd

df = pd.DataFrame({'Date': ['Apr 2022', 'Dec 2021', 'May 2022', 'May 2021'], 'Price': [2, 8, 12, 15]})

df = df.sort_values(by='Date', ignore_index=True, key=pd.to_datetime)

print(df)
#        Date  Price
# 0  May 2021     15
# 1  Dec 2021      8
# 2  Apr 2022      2
# 3  May 2022     12

Relevant documentation:

Stef
  • 13,242
  • 2
  • 17
  • 28