如何在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.

