# import packages
importnumpyasnpimportpandasaspdfromcalendarimportmonth_abbr# load data
month_numbers=np.arange(1,13)month_names=[month_abbr[i]foriinmonth_numbers]defmonthly_mean(station_name,freq):# import daily data
df=pd.read_csv(station_name+'_'+freq+'.csv',sep=",")# make 'DATE' the dataframe index
df['DATE']=pd.to_datetime(df['DATE'])df=df.set_index('DATE')# print(df.index[0], df.index[-1])
iffreq=='daily':# resample data by month
df_month=df['PRCP'].resample('M').sum()# sum is labeled at the last day of the month
df_month=df_month/10# PRCP is given in tens of mm (see readme)
iffreq=='monthly':df_month=df['PRCP']# calculate monthly mean
monthly_mean=np.array([])# empty array
forminmonth_numbers:# cycle over months (1, 2, 3, etc)
this_month_all_indices=(df_month.index.month==m)# indices in df_month belonging to month m
this_month_mean=df_month[this_month_all_indices].mean()# this is the monthly mean
monthly_mean=np.append(monthly_mean,this_month_mean)# append
# make new df and return it
df_return=pd.DataFrame({'monthly rainfall (mm)':monthly_mean,'month names':month_names,'month number':month_numbers})returndf_return# load monthly mean
df_london=monthly_mean("LONDON HEATHROW",'monthly')df_telaviv=monthly_mean("TEL AVIV READING",'monthly')#collapse-hide
defwalsh_index(df):m=df["monthly rainfall (mm)"]R=df["monthly rainfall (mm)"].sum()SI=np.sum(np.abs(m-R/12))/RreturnSIlondon_index=walsh_index(df_london)telaviv_index=walsh_index(df_telaviv)print("Seasonality index (Walsh and Lawler, 1981)")print(f"London: {london_index:.2f}")print(f"Tel Aviv: {telaviv_index:.2f}")