0% found this document useful (0 votes)
10 views2 pages

save dist figures

Uploaded by

gunjanc080
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views2 pages

save dist figures

Uploaded by

gunjanc080
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import numpy as np

import matplotlib.pyplot as plt


from distfit import distfit
import pandas as pd

# Load the data from CSV with error handling


try:
df1 = pd.read_csv('D:\\pythonProject1\\venv\\Rain_imd\\IMD_DataSET\\
Sarotry_monthly_tmp_prp.csv')
except FileNotFoundError:
print("The specified file was not found. Please check the path.")
exit()
except pd.errors.EmptyDataError:
print("The file is empty. Please check the file.")
exit()

# Set the columns based on your description


df1.columns = ['Month', 'prp', 'tmin', 'tmax', 'flow']
df1['Month'] = pd.to_datetime(df1['Month'], format='%B-%Y') # Convert to datetime

# Initialize the distfit object


df = distfit()

# List of monsoon months (June to September)


monsoon_months = [6, 7, 8, 9]

# Create a list to hold the results for each variable and month
results = []

# List of variables to analyze


variables = ['prp', 'tmin', 'tmax', 'flow']

# Create a plot for each monsoon month and each variable


for month in monsoon_months:
for var in variables:
monthly_data = df1[df1['Month'].dt.month == month][var].to_numpy()
monthly_data = monthly_data[~np.isnan(monthly_data)] # Remove NaN values
if present

# Check if there is data to fit


if len(monthly_data) > 0:
# Fit the data to a distribution
df.fit_transform(monthly_data)

# Get summary of the fitted distributions


summary = df.summary
best_fit = summary.iloc[0] # Get the best fitting distribution

# Collect results for the month and variable


results.append({
'Month': df1['Month'].dt.month_name()[month - 1], # Month name
'Variable': var,
'Best Distribution': best_fit['name'],
'Parameters': best_fit['params']
})

# Plot the results


plt.figure()
df.plot()
plt.title(f"Distribution Fit for {df1['Month'].dt.month_name()[month -
1]} - {var}") # Month and variable name
plt.xlabel(f"{var} values")
plt.ylabel("Density")
plt.tight_layout() # Improve layout

# Save the figure


plt.savefig(f"Distribution_Fit_{df1['Month'].dt.month_name()[month -
1]}_{var}.png") # Save figure as PNG
plt.close() # Close the figure to avoid displaying it

else:
print(f"No data available for {df1['Month'].dt.month_name()[month - 1]}
in {var}")

# Create a DataFrame from the results


results_df = pd.DataFrame(results)

# Print the summary DataFrame


print("\nSummary of Best Fitting Distributions for Monsoon Months:")
print(results_df)

# Export the results to a CSV file


results_df.to_csv('monsoon_distribution_fits_all_variables.csv', index=False)
print("\nResults have been exported to
'monsoon_distribution_fits_all_variables.csv'.")

# Optionally, show all plots (if you wish to see them)


# plt.show()

You might also like