如何用Pandas基于唯一ID的日期生成向前4天的多日期序列?
Hey there! Let's get this sorted out. The issue you're facing likely comes from two key points: your Date column is probably stored as string instead of datetime type, and your pd.date_range call was generating dates in the wrong direction. Here's how to fix it step by step:
第一步:确保日期列是datetime类型
First, convert your Date column to datetime format—this is critical because pd.date_range can't work directly with string dates:
df['Date'] = pd.to_datetime(df['Date'])
第二步:生成正确的回溯日期序列
Rewrite your function to generate 5 consecutive dates starting 4 days before the original date (inclusive). Using end=row['Date'] tells date_range to stop at the original date, and periods=5 grabs the 5 days leading up to it:
def generate_backward_dates(row): # Generate 5 dates ending at the original date (4 days back + original date) return pd.date_range(end=row['Date'], periods=5, freq='D') df['Date_list'] = df.apply(generate_backward_dates, axis=1)
第三步:展开列表为多行
Use explode() to turn each list of dates into separate rows, then clean up the columns:
# Explode the date list into individual rows result_df = df.explode('Date_list').rename(columns={'Date_list': 'Date'}) # Reset index to clean up the output result_df = result_df.reset_index(drop=True)
完整示例代码
Here's the full working code with sample data:
import pandas as pd # Sample input DataFrame df = pd.DataFrame({ 'ID': [11, 22, 33], 'Date': ['3/19/2018', '1/5/2018', '2/12/2018'] }) # Convert Date to datetime df['Date'] = pd.to_datetime(df['Date']) # Generate backward date ranges def generate_backward_dates(row): return pd.date_range(end=row['Date'], periods=5, freq='D') df['Date_list'] = df.apply(generate_backward_dates, axis=1) # Explode and clean up result_df = df.explode('Date_list').rename(columns={'Date_list': 'Date'}).reset_index(drop=True) print(result_df)
This will output exactly the format you're looking for, with each ID having 5 consecutive dates starting 4 days before its original date.
内容的提问来源于stack exchange,提问作者qqqwww

