You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pandas基于唯一ID的日期生成向前4天的多日期序列?

解决方法:生成每个ID的回溯日期序列

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:11:43