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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics