Order Rows of pandas DataFrame by Date in Python (Example Code)

In this article you’ll learn how to sort a pandas DataFrame by a date column in Python.

Preparing the Example

import pandas as pd                                                  # Import pandas library in Python
my_df = pd.DataFrame({'A':['01/01/2025','01/01/2023','01/01/2024'],  # Construct example DataFrame in Python
                      'B':range(11, 14)})
print(my_df)                                                         # Display example DataFrame in console
#             A   B
# 0  01/01/2025  11
# 1  01/01/2023  12
# 2  01/01/2024  13

Example: Sorting Rows of pandas DataFrame by Date Column

my_df['dates'] = pd.to_datetime(my_df.A)                             # Convert column to date
my_df = my_df.sort_values(by = ['A'])                                # Order rows by dates
print(my_df)                                                         # Display ordered data
#             A   B      dates
# 1  01/01/2023  12 2023-01-01
# 2  01/01/2024  13 2024-01-01
# 0  01/01/2025  11 2025-01-01

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top