'Python: Order Dates that are in the format: %B %Y
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.
Solution 1:[1]
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:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Stef |