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

如何在Pandas DataFrame中追加连续日期?示例解析

Solution: Append Consecutive Dates to Pandas DataFrame

The issue with your existing code is that pd.date_range() includes the start date in its result. When you use your last existing date (2001-01-04) as the start and set periods=2, you end up with the duplicate date 2001-01-04 plus one new date—but you need two entirely new consecutive dates after the last entry. Here's how to fix it:

Step-by-Step Implementation

1. Ensure your date column is datetime type

First, confirm your Dates column is formatted as datetime (critical for date arithmetic):

import pandas as pd

# Original DataFrame (replace with your actual DataFrame)
dates = pd.DataFrame({'Dates': ['2001-01-01', '2001-01-02', '2001-01-03', '2001-01-04']})
dates['Dates'] = pd.to_datetime(dates['Dates'])

2. Get the last date from your DataFrame

Extract the final date to use as a starting point for new dates:

last_date = dates['Dates'].iloc[-1]

3. Generate the two new consecutive dates

Start the date range the day after the last existing date, and specify 2 periods:

new_dates = pd.date_range(start=last_date + pd.Timedelta(days=1), periods=2)

This will produce 2001-01-05 and 2001-01-06 exactly as you need.

4. Append the new dates to your original DataFrame

Convert the date range to a matching DataFrame structure, then combine using pd.concat() (since append() is deprecated in newer Pandas versions):

new_df = pd.DataFrame({'Dates': new_dates})
updated_dates = pd.concat([dates, new_df], ignore_index=True)

Full Working Code

import pandas as pd

# Original DataFrame
dates = pd.DataFrame({'Dates': ['2001-01-01', '2001-01-02', '2001-01-03', '2001-01-04']})
dates['Dates'] = pd.to_datetime(dates['Dates'])

# Get last date and generate new dates
last_date = dates['Dates'].iloc[-1]
new_dates = pd.date_range(start=last_date + pd.Timedelta(days=1), periods=2)

# Combine DataFrames
new_df = pd.DataFrame({'Dates': new_dates})
updated_dates = pd.concat([dates, new_df], ignore_index=True)

print(updated_dates)

Output

Dates
0 2001-01-01
1 2001-01-02
2 2001-01-03
3 2001-01-04
4 2001-01-05
5 2001-01-06

Content of the question comes from Stack Exchange, question author Roman.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 10:02:20