Below is a Python script that processes the Excel file according to your requirements. It uses pandas for data manipulation and openpyxl or xlsxwriter for saving the output to Excel. The script fills short gaps (<5 days) with linear interpolation and long gaps (≥5 days) with the historical mean discharge for the corresponding calendar day.
import pandas as pd
def fill_discharge_data(input_file, output_file):
# Read the Excel file, skipping the first 5 rows of metadata
df = pd.read_excel(input_file, skiprows=5, parse_dates=[0], index_col=0)
# Ensure the index is a DatetimeIndex
df.index = pd.to_datetime(df.index)
# Process each column (hydrological post)
for column in df.columns:
series = df[column]
# Calculate the mean discharge for each calendar day over the entire period
historical_means = series.groupby(series.index.strftime('%m-%d')).mean()
# Identify gaps in the data
gaps = series.isna()
# Fill gaps based on their length
for gap_start in pd.date_range(start=series.index.min(), end=series.index.max(), freq='D'):
if gap_start in series.index and pd.isna(series.loc[gap_start]):
# Find the end of the current gap
gap_end = gap_start
while gap_end + pd.Timedelta(days=1) in series.index and pd.isna(series.loc[gap_end + pd.Timedelta(days=1)]):
gap_end += pd.Timedelta(days=1)
gap_length = (gap_end - gap_start).days + 1
gap_range = pd.date_range(start=gap_start, end=gap_end)
if gap_length < 5:
# Fill short gaps with linear interpolation
valid_before = series.loc[:gap_start].last_valid_index()
valid_after = series.loc[gap_end:].first_valid_index()
if valid_before is not None and valid_after is not None:
slope = (series.loc[valid_after] - series.loc[valid_before]) / (valid_after - valid_before).days
for date in gap_range:
days_since_before = (date - valid_before).days
series.loc[date] = series.loc[valid_before] + slope * days_since_before
elif valid_before is not None:
series.loc[gap_range] = series.loc[valid_before] # Forward fill
elif valid_after is not None:
series.loc[gap_range] = series.loc[valid_after] # Backward fill
else:
# Fill long gaps with historical mean for the calendar day
for date in gap_range:
calendar_day = date.strftime('%m-%d')
if calendar_day in historical_means:
series.loc[date] = historical_means[calendar_day]
else:
# If no historical data for this calendar day, fill with overall mean
series.loc[date] = series.mean()
# Update the DataFrame with the filled series
df[column] = series
# Save the filled data to a new Excel file
df.to_excel(output_file)
# Example usage:
# fill_discharge_data('input.xlsx', 'output.xlsx')
Explanation:
- Reading Data: The Excel file is read while skipping the first 5 rows of metadata. The first column is assumed to be dates and is set as the index.
- Historical Means: For each calendar day (e.g., February 5th), the mean discharge is calculated across all years in the dataset.
- Gap Detection: Gaps in the data are identified using
isna().
- Filling Gaps:
- Short Gaps (<5 days): Filled using linear interpolation between the nearest valid values before and after the gap.
- Long Gaps (≥5 days): Filled with the historical mean discharge for the corresponding calendar day. If no historical data exists for that calendar day, the overall mean discharge for the post is used.
- Saving Output: The filled data is saved to a new Excel file.
Requirements:
Install the required libraries using pip:
pip install pandas openpyxl
This script assumes the first column of your Excel sheet contains dates and the subsequent columns contain discharge data for different hydrological posts. Adjust the code if your data structure differs.