Python Code to Insert Missing Dates in a Time Series CSV
Here's a Python script that reads a CSV file with a time series (one step per day), identifies missing dates, inserts them with empty values, and saves the result to a new CSV file:
import pandas as pd
from datetime import datetime, timedelta
def insert_missing_dates(input_csv, output_csv, date_column='date', value_column='value'):
"""
Insert missing dates into a time series CSV without filling the gaps.
Parameters:
- input_csv: Path to the input CSV file
- output_csv: Path to save the output CSV file
- date_column: Name of the column containing dates (default: 'date')
- value_column: Name of the column containing values (default: 'value')
"""
# Read the input CSV file
df = pd.read_csv(input_csv)
# Convert the date column to datetime
df[date_column] = pd.to_datetime(df[date_column])
# Sort by date to ensure chronological order
df = df.sort_values(date_column).reset_index(drop=True)
# Create a complete date range from min to max date
min_date = df[date_column].min()
max_date = df[date_column].max()
all_dates = pd.date_range(start=min_date, end=max_date, freq='D')
# Create a new DataFrame with all dates
complete_df = pd.DataFrame({date_column: all_dates})
# Merge with original data to find missing dates
complete_df = complete_df.merge(
df[[date_column, value_column]],
on=date_column,
how='left'
)
# Save to new CSV file
complete_df.to_csv(output_csv, index=False)
print(f"Processed file saved to {output_csv}")
# Example usage:
# insert_missing_dates('input.csv', 'output_with_missing_dates.csv')
How to Use This Code:
- Save this code to a Python file (e.g.,
insert_missing_dates.py)
- Call the function with your input and output file paths:
insert_missing_dates('your_input_file.csv', 'output_file.csv')
- If your date column has a different name than 'date', specify it:
insert_missing_dates('input.csv', 'output.csv', date_column='your_date_column_name')
Notes:
- The script assumes your CSV has at least two columns: one for dates and one for values
- Missing dates will be inserted with NaN (empty) values in the value column
- The output will maintain the original data while adding rows for missing dates
- The dates in the output will be in chronological order
If your CSV has a different structure or you need to handle additional columns, the function can be modified accordingly.