import pandas as pd import numpy as np import matplotlib.pyplot as plt from…
- User
import pandas as pd import numpy as np import matplotlib.pyplot as plt from statsmodels.tsa.arima.model import ARIMA
Function to load and preprocess the data
def load_and_preprocess_data(file_path): # Load the CSV file df = pd.read_csv(file_path)
# Convert date column to datetime df['Date'] = pd.to_datetime(df['Date'], format='%d-%m-%Y') # Replace 'Tr' and other invalid entries with NaN and fill missing values df.replace({'Rain': {'Tr': np.nan, '-----': np.nan}}, inplace=True) df.replace({'Temp_Max': {'Tr': np.nan, '-----': np.nan}, 'Temp_Min': {'Tr': np.nan, '-----': np.nan}}, inplace=True) # Convert numeric columns to floats df['Rain'] = pd.to_numeric(df['Rain'], errors='coerce') df['Temp_Max'] = pd.to_numeric(df['Temp_Max'], errors='coerce') df['Temp_Min'] = pd.to_numeric(df['Temp_Min'], errors='coerce') # Drop any rows with NaN values df.dropna(inplace=True) return dfFunction to plot each month separately for Temp_Max and Temp_Min
def plot_each_month_separately(df): months = range(1, 13)
fig, axs = plt.subplots(nrows=12, ncols=1, figsize=(12, 36), sharex=True, sharey=True) # Changed to 1x12 grid fig.suptitle('Monthly Temperature Data') for i, month in enumerate(months): # No need to calculate row and column index anymore month_data = df[df['Date'].dt.month == month] axs[i].plot(month_data['Date'], month_data['Temp_Max'], marker='o', label=f'Temp Max') axs[i].plot(month_data['Date'], month_data['Temp_Min'], marker='o', label=f'Temp Min', color='red') axs[i].set_title(f'Month {month}') axs[i].set_xlabel('Year') axs[i].set_ylabel('Temperature (°C)') plt.tight_layout(rect=[0.04, 0.04, 1, 0.98]) plt.show()Function to predict future temperatures using ARIMA
def predict_future_temperatures(df): # Split the data into train and test sets for Temp_Max and Temp_Min train_years = 50 # Using the last 50 years as training data train_size = int(len(df) * (train_years / 68)) # Assuming a total of 68 years in the dataset
train_temp_max = df['Temp_Max'].iloc[:train_size] test_temp_max = df['Temp_Max'].iloc[train_size:] train_temp_min = df['Temp_Min'].iloc[:train_size] test_temp_min = df['Temp_Min'].iloc[train_size:] # Fit ARIMA model for Temp_Max try: model_temp_max = ARIMA(train_temp_max, order=(5, 1, 0)) model_fit_temp_max = model_temp_max.fit() # Forecast for the next 240 months (20 years * 12 months/year) forecast_temp_max = model_fit_temp_max.forecast(steps=240).values except: print("ARIMA model failed to fit Temp_Max. Using moving average instead.") forecast_temp_max = train_temp_max.rolling(window=5, center=False).mean().iloc[-1:].repeat(240).values # Fit ARIMA model for Temp_Min try: model_temp_min = ARIMA(train_temp_min, order=(5, 1, 0)) model_fit_temp_min = model_temp_min.fit() # Forecast for the next 240 months (20 years * 12 months/year) forecast_temp_min = model_fit_temp_min.forecast(steps=240).values except: print("ARIMA model failed to fit Temp_Min. Using moving average instead.") forecast_temp_min = train_temp_min.rolling(window=5, center=False).mean().iloc[-1:].repeat(240).values # Create a future date range for the predictions end_date = df['Date'].max() future_dates = pd.date_range(start=end_date + pd.Timedelta(days=1), periods=240, freq='M') return future_dates, forecast_temp_max, forecast_temp_min - Assistant