Okay, this is a classic data processing task well-suited for Python and the Pandas library.
Here's the plan:
- Setup: Import necessary libraries (
os, pandas, pathlib).
- File Discovery: Use
pathlib to find all CSV files in a specified folder.
- Main Loop: Iterate through each found CSV file.
- Data Loading (per file):
- Read the CSV using Pandas, specifying the semicolon separator and no header.
- Assign appropriate column names.
- Convert
precipitation to a numeric type, making sure empty strings or non-numeric values become NaN (Not a Number).
- Create a proper
datetime column from year, month, day, hour for easier manipulation.
- Winter Identification:
- Filter data for winter months (December, January, February).
- Define a "winter season" label (e.g., "2022-2023") for each row. December belongs to the winter starting that year, while January and February belong to the winter that started the previous year.
- Winter Processing (per winter season in a file):
- Group the data by the "winter season" label.
- For each winter season group:
- Get the station index (it's constant per file, so pick from the first row).
- Calculate the total number of expected precipitation records.
- Calculate the number of missing precipitation records (
NaNs).
- Calculate the percentage of gaps.
- Gap Filling:
- If gap percentage is <= 20%:
- Create a copy of the precipitation data for this winter to avoid modifying the original in a way that affects other calculations if needed (though
transform is usually safe).
- Calculate the mean precipitation for each month within this specific winter.
- Use
transform to fill NaN values in the precipitation column with the corresponding monthly mean for that winter.
- Important Consideration: If an entire month within this winter has no precipitation data at all, its monthly mean will be
NaN, and thus gaps for that month won't be filled. The overall winter average will then be calculated based on the available (and filled) data.
- Calculate the average precipitation for the entire winter using the (potentially) filled data.
- If gap percentage is > 20%:
- The average precipitation for this winter is "Too many gaps".
- Store the result (station index, winter season, calculated average precipitation or status).
- Aggregation: Collect all results from all files and all winters.
- Output: Create a Pandas DataFrame from the aggregated results and save it to a new CSV file.
Let's write the code.
import pandas as pd
import os
from pathlib import Path
# --- Configuration ---
INPUT_FOLDER = 'weather_data' # Folder containing your CSV files
OUTPUT_FILE = 'winter_precipitation_summary.csv'
COLUMN_NAMES = ['station_index', 'year', 'month', 'day', 'hour',
'wind_speed', 'precipitation', 'air_temperature']
MAX_GAP_PERCENTAGE = 20.0
# --- Helper Function to define winter season ---
def get_winter_season(row):
"""
Assigns a winter season label (e.g., '2022-2023').
Winter is Dec, Jan, Feb.
Dec 2022 is part of winter 2022-2023.
Jan 2023 is part of winter 2022-2023.
Feb 2023 is part of winter 2022-2023.
"""
month = row['month']
year = row['year']
if month == 12:
return f"{year}-{year + 1}"
elif month == 1 or month == 2:
return f"{year - 1}-{year}"
return None # Not a winter month for this definition
def process_file(file_path):
"""
Processes a single CSV file to calculate winter precipitation.
"""
results_for_file = []
try:
# 1. Load data
df = pd.read_csv(file_path, sep=';', header=None, names=COLUMN_NAMES, na_filter=True)
if df.empty:
print(f"Warning: File {file_path.name} is empty. Skipping.")
return []
# 2. Data type conversion
# Ensure 'precipitation' is numeric, converting non-numeric to NaN
# Empty strings in CSV often read as objects, so coerce to numeric
df['precipitation'] = pd.to_numeric(df['precipitation'], errors='coerce')
# Ensure year, month, day, hour are integers for datetime creation
for col in ['year', 'month', 'day', 'hour']:
df[col] = pd.to_numeric(df[col], errors='coerce').fillna(0).astype(int) # Fill potential NaNs before int conversion
# Check for station index consistency if needed, or just take the first one
station_id = df['station_index'].iloc[0] if not df.empty else "Unknown"
# 3. Create datetime column (optional but good practice, helps if sorting is needed)
# Handle potential errors if date components are invalid after coercion
try:
df['datetime'] = pd.to_datetime(df[['year', 'month', 'day', 'hour']])
except ValueError as e:
print(f"Warning: Could not create datetime for {file_path.name} due to invalid date parts. Skipping file. Error: {e}")
return []
# 4. Identify winter months and assign winter season
df_winter_months = df[df['month'].isin([12, 1, 2])].copy() # Work on a copy
if df_winter_months.empty:
print(f"No winter data in {file_path.name}. Skipping.")
return []
df_winter_months['winter_season'] = df_winter_months.apply(get_winter_season, axis=1)
# 5. Process each winter season
for season, winter_data in df_winter_months.groupby('winter_season'):
total_records = len(winter_data)
missing_precip_count = winter_data['precipitation'].isnull().sum()
gap_percentage = (missing_precip_count / total_records) * 100 if total_records > 0 else 0
avg_winter_precip = None
if gap_percentage <= MAX_GAP_PERCENTAGE:
# Fill gaps with monthly average for THIS winter
filled_precipitation = winter_data['precipitation'].copy() # Work on a copy for filling
# Calculate monthly means *only from non-NaN values within this winter*
monthly_means = winter_data.groupby('month')['precipitation'].transform('mean')
# Fill NaNs using these calculated monthly means
filled_precipitation.fillna(monthly_means, inplace=True)
# If there are still NaNs (e.g., a whole month was NaN, so its mean was NaN)
# the final .mean() will ignore them, which is fine.
avg_winter_precip = filled_precipitation.mean()
if pd.isna(avg_winter_precip) and total_records > 0 and missing_precip_count < total_records:
# This could happen if all non-NaN months had their data, but the NaN months
# were entirely NaN, so monthly_means for those months were NaN.
# And if ALL data became NaN after fill (highly unlikely unless all data was initially NaN)
# In such a rare case, treat as too many gaps if there was *some* data initially.
# Or, if ALL precipitation was NaN initially (even if <20% of records), avg will be NaN.
# Let's check if all values in filled_precipitation are NaN
if filled_precipitation.isnull().all() and total_records > 0 :
avg_winter_precip = "Effectively all gaps after attempted fill"
# else, a NaN mean is fine if, for instance, all precip values were 0 or truly missing.
else:
avg_winter_precip = f"Too many gaps ({gap_percentage:.1f}%)"
results_for_file.append({
'station_index': station_id,
'winter_season': season,
'average_winter_precipitation': avg_winter_precip if pd.notna(avg_winter_precip) else 'N/A (e.g. all precip was NaN)'
})
except pd.errors.EmptyDataError:
print(f"Warning: File {file_path.name} is empty or malformed (EmptyDataError). Skipping.")
return []
except Exception as e:
print(f"Error processing file {file_path.name}: {e}")
return []
return results_for_file
def main():
"""
Main function to orchestrate the processing.
"""
input_path = Path(INPUT_FOLDER)
if not input_path.is_dir():
print(f"Error: Input folder '{INPUT_FOLDER}' not found.")
# Create dummy folder and files for testing if it doesn't exist
print(f"Creating dummy folder '{INPUT_FOLDER}' and files for testing.")
input_path.mkdir(parents=True, exist_ok=True)
# Create dummy CSV files
dummy_data_1 = [
"ST001;2021;12;1;0;5.0;1.0;2.0",
"ST001;2021;12;1;1;5.1;;3.0", # Gap
"ST001;2022;1;15;0;6.0;2.5;-1.0",
"ST001;2022;1;15;1;6.2;3.0;-2.0",
"ST001;2022;2;10;0;4.0;0.5;0.0",
"ST001;2022;2;10;1;4.1;0.8;0.5",
"ST001;2022;3;1;0;3.0;0.1;5.0", # Not winter
]
with open(input_path / "station1_data.csv", "w") as f:
f.write("\n".join(dummy_data_1))
dummy_data_2_too_many_gaps = [
"ST002;2022;12;1;0;5.0;;2.0", # Gap
"ST002;2022;12;1;1;5.1;;3.0", # Gap
"ST002;2023;1;15;0;6.0;2.5;-1.0",
"ST002;2023;1;15;1;6.2;;-2.0", # Gap
"ST002;2023;2;10;0;4.0;;0.0", # Gap - 4 gaps out of 5 records = 80%
"ST002;2023;2;10;1;4.1;0.8;0.5", # This record is actually in the next winter if it's Dec
]
# Correcting data for a single winter
dummy_data_2_one_winter_gappy = [
"ST002;2022;12;1;0;5.0;;2.0", # Winter 2022-2023
"ST002;2022;12;1;1;5.1;;3.0", # Winter 2022-2023
"ST002;2023;1;15;0;6.0;2.5;-1.0",# Winter 2022-2023
"ST002;2023;1;15;1;6.2;;-2.0", # Winter 2022-2023
"ST002;2023;2;10;0;4.0;;0.0" , # Winter 2022-2023 - 4 gaps out of 5 records
]
with open(input_path / "station2_data_gappy.csv", "w") as f:
f.write("\n".join(dummy_data_2_one_winter_gappy))
dummy_data_3_all_gaps_one_month = [ # test case where one month is completely NaN
"ST003;2023;12;1;0;5.0;1.0;2.0", # Dec
"ST003;2023;12;2;0;5.0;1.5;2.0", # Dec
"ST003;2024;1;1;0;6.0;;-1.0", # Jan - All NaN
"ST003;2024;1;2;0;6.2;;-2.0", # Jan - All NaN
"ST003;2024;2;10;0;4.0;0.5;0.0", # Feb
"ST003;2024;2;11;0;4.0;0.7;0.0", # Feb
] # 2 gaps / 6 records = 33% (too many if MAX_GAP_PERCENTAGE = 20)
# if MAX_GAP_PERCENTAGE = 35, then Jan gaps remain, avg is of Dec and Feb
with open(input_path / "station3_data_month_nan.csv", "w") as f:
f.write("\n".join(dummy_data_3_all_gaps_one_month))
all_results = []
csv_files = list(input_path.glob('*.csv'))
if not csv_files:
print(f"No CSV files found in '{INPUT_FOLDER}'.")
return
print(f"Found {len(csv_files)} CSV files to process.")
for file_path in csv_files:
print(f"Processing {file_path.name}...")
results_for_file = process_file(file_path)
all_results.extend(results_for_file)
if not all_results:
print("No winter data processed or found across all files.")
return
# Create output DataFrame
output_df = pd.DataFrame(all_results)
# Save to CSV
try:
output_df.to_csv(OUTPUT_FILE, index=False)
print(f"\nResults successfully saved to {OUTPUT_FILE}")
except Exception as e:
print(f"\nError saving results to {OUTPUT_FILE}: {e}")
if __name__ == '__main__':
# --- Create dummy folder and files for testing if INPUT_FOLDER does not exist ---
# This part is moved into main() so it only runs if the folder is missing.
# The `main()` function will now create these if the folder is absent.
main()
How to Use:
- Save the code: Save the Python script (e.g.,
process_weather.py).
- Create a folder: Create a folder named
weather_data (or change INPUT_FOLDER in the script) in the same directory as your script.
- Place CSV files: Put your semicolon-separated CSV files (without headers) into the
weather_data folder.
- If you run the script and the
weather_data folder doesn't exist, it will create it and add some dummy CSV files for testing purposes.
- Run the script: Execute
python process_weather.py from your terminal.
- Check output: A file named
winter_precipitation_summary.csv will be created in the same directory as the script, containing the results.
Explanation of Key Pandas Parts:
pd.read_csv(file_path, sep=';', header=None, names=COLUMN_NAMES): Reads the CSV.
sep=';': Specifies the semicolon delimiter.
header=None: Indicates no header row in the CSVs.
names=COLUMN_NAMES: Assigns your defined column names.
pd.to_numeric(df['precipitation'], errors='coerce'): Converts the precipitation column to numbers. errors='coerce' turns any value that cannot be converted into NaN.
df['datetime'] = pd.to_datetime(df[['year', 'month', 'day', 'hour']]): Combines individual date/time columns into a single Pandas datetime object, which is very powerful.
df['month'].isin([12, 1, 2]): Creates a boolean Series to filter rows for winter months.
df_winter_months.apply(get_winter_season, axis=1): Applies the get_winter_season function row-wise to create the winter_season label.
df_winter_months.groupby('winter_season'): Groups the data by the winter_season label. The subsequent loop iterates through each group (each unique winter).
winter_data['precipitation'].isnull().sum(): Counts NaN values in the precipitation column for the current winter group.
winter_data.groupby('month')['precipitation'].transform('mean'): This is crucial for filling gaps.
groupby('month'): Groups data within the current winter by month.
['precipitation']: Selects the precipitation column.
.transform('mean'): For each original row in winter_data, it calculates the mean of its group (i.e., the mean precipitation for its month within that winter) and "broadcasts" this mean back to all rows belonging to that month. This means all entries for January in winter "2022-2023" will get the same January 2022-2023 average.
filled_precipitation.fillna(monthly_means, inplace=True): Fills the NaN values in the filled_precipitation Series using the monthly_means Series (which was aligned by the transform operation).
filled_precipitation.mean(): Calculates the final average precipitation for the winter, using the data where gaps might have been filled. Pandas' mean() by default skips NaN values, which is useful if a whole month was NaN and couldn't be filled by its own monthly average.
This script is robust and handles several edge cases like empty files, files with no winter data, and provides informative print statements.