w3resource

Checking Date Order in a Column Using Pandas

Pandas: Data Validation Exercise-14 with Solution

Write a Pandas program to check consistent date order in a column.

Note: Chronological order is a way that follows the order in which a series of events happened.

This exercise demonstrates how to validate that dates in a column are in chronological order.

Sample Solution :

Code :

import pandas as pd
# Create a sample DataFrame with dates
df = pd.DataFrame({
    'Event': ['Start', 'Middle', 'End'],
    'Date': ['2020-01-01', '2020-01-15', '2020-01-10']
})

# Convert the 'Date' column to datetime
df['Date'] = pd.to_datetime(df['Date'], errors='coerce')

# Check if the dates are in chronological order
chronological_order = df['Date'].is_monotonic_increasing

# Output the result
print(f"Are the dates in chronological order? {chronological_order}")

Output:

Are the dates in chronological order? False

Explanation:

  • Created a DataFrame with date strings.
  • Converted the 'Date' column to datetime format using to_datetime().
  • Used is_monotonic_increasing to check if the dates are in chronological order.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/pandas/pandas-check-date-order-in-a-dataframe-column.php