Hi I am trying to read precipitation files from a folder and calculate total precipitation for a year. Using os and pandas to loop through sub director and read files. Each file contains data for 1 year. Then calculating total precipitation for each year.
I am also trying to get a list of years where total precipitation is zero. So I declared an empty list (zero_year = []
) then used if condition to append years where total precipitation is zero to the empty list.
My problem is that the zero_year switches to class 'NoneType' inside the if statement and will not allow me to append the years with zero precipitation to zero_year list.
I think I am missing something very basic. Appreciate any help I can get.
#Walk through all subfolders and files under the "Precipitation" directory
#1st loop gets list of sub directory under precipitation
#2nd loop is for files under the sub directory
import os
import pandas as pd
filepath = "Precipitation\\"
global zero_year
for sub_directory in os.listdir(filepath):
sub_filepath = (filepath+sub_directory)
zero_year = []
print(type(zero_year))
for filename in os.listdir(sub_filepath):
full_filepath = (sub_filepath+ "\\" +filename)
current_year = filename[6:8]+ filename[9:]
#Read Precipitation File
precip_file = pd.read_csv(full_filepath,sep = " ",header = None,skipinitialspace = True,names = ["Day","Precip (mm)"],index_col=False)
#Remove the last row that has no data using drop
precip_file.drop(precip_file.tail(1).index,inplace=True)
#Convert all strings to no data ---- NaN
precip_file =precip_file.apply(pd.to_numeric,errors = "coerce")
#Sum all precipitation value in file to get total precipitation value for a year
yearly_total = precip_file["Precip (mm)"].sum(skipna=True)
#List years where total precipitation is zero
if yearly_total == 0:
zero_year = zero_year.extend(current_year)
print(type(zero_year))
print(zero_year)
Aucun commentaire:
Enregistrer un commentaire