如何在Python DataFrame中判断date1列日期是否处于date2列日期的±10天范围内
Got it, let's walk through how to solve this problem step by step. The core goal is to verify if each date in the date1 column falls within a 10-day window (either before or after) the corresponding date in the date2 column.
Step 1: Convert date columns to datetime type
First up, we need to turn those string dates into proper datetime objects—strings can't be used to calculate date differences reliably. We'll use pd.to_datetime() and explicitly set the format parameter since our dates follow the DD/MM/YYYY pattern.
Step 2: Calculate date differences and check the 10-day condition
Once we have datetime-formatted columns, we can compute the absolute difference between date1 and date2, extract the number of days from that difference, and check if it's 10 or less.
Full code example
import pandas as pd # Create the sample DataFrame from your scenario df = pd.DataFrame({ 'date1': ['13/08/2021'], 'date2': ['21/08/2021'] }) # Convert string dates to datetime objects df['date1'] = pd.to_datetime(df['date1'], format='%d/%m/%Y') df['date2'] = pd.to_datetime(df['date2'], format='%d/%m/%Y') # Add a new column with the boolean check result df['within_10_days'] = abs(df['date1'] - df['date2']).dt.days <= 10 # Print the result print(df['within_10_days'])
Why the sample returns True
In your example, the difference between 13/08/2021 and 21/08/2021 is 8 days—this is well within the ±10 day range, so the output will be a Series with the value True.
This logic works for multiple rows too: it will check each pair of dates individually and return a boolean value for every entry in your DataFrame.
内容的提问来源于stack exchange,提问作者Souvik Pal

