calculating rolling average using python -
i've started learning python. using write script calculate salt inflow rolling average. have data that
date a4260502_flow a4261051_flow a4260502_ec a4261051_ec 25/02/1970 1304 0 411 0 1304 26/02/1970 1331 0 391 0 1331 27/02/1970 0 0 420 411 0 28/02/1970 0 0 400 391 0 1/03/1970 0 0 0 420 0 2/03/1970 1351 1304 405 400 1327.5 3/03/1970 2819 1331 415 405 2075 4/03/1970 2816 0 413 0 2816 5/03/1970 0 1351 0 415 1351 6/03/1970 0 0 0 0 0 7/03/1970 0 2819 0 413 2819 8/03/1970 0 0 0 0 0 9/03/1970 0 2816 0 412 2816
and script is
inputfilename = "output.csv" outputfilename = "si_calculation.csv" # open files infile = open(inputfilename,"r+") outfile = open(outputfilename,'w') # initialise variables ec_conversion = 0.000525 rolling_avg = 5 flow_avg_list = [] si_list = [] si_ra_list = [] si_ra1 = [] # import module import csv import numpy #l20 table = [] reader = csv.reader(infile) #read row in csv.reader(infile): table.append(row) infile.close() r in range(1,len(table)): c in range(1,len(row)): #l30 table[r][c] = float(table[r][c]) #calculating flow average r in range(1,len(table)): flow1 = table[r][1] flow2 = table[r][2] if flow1 == 0.0: flow_avg = flow2 #l40 elif flow2 == 0.0: flow_avg = flow1 else: flow_avg = (flow1+flow2)/2 flow_avg_list.append(flow_avg) #calculating salt inflow r in range(1,len(table)): s1 = table[r][3] s2 = table[r][4] #l50 if s1 == 0.0 or s2 == 0.0 or flow_avg_list[r-1] == 0.0: si = 0.0 else: si = ec_conversion*flow_avg_list[r-1]*(s2-s1) si_list.append(si) print si_list #calculating rolling average salt inflow r in range(1,len(table)): if r < 5: #rolling-avg = 5 in range(0,r+5): #l60 s = si_list[i] si_ra1.append(s) si_ra = numpy.mean(si_ra1) si_ra_list.append(si_ra) elif r > (len(table) - 4): in range(r-5,len(table)-1): s = si_list[i] si_ra1.append(s) si_ra = numpy.mean(si_ra1) si_ra_list.append(si_ra) #l70 else: in range(r-5,r+5): s = si_list[i] #line 73 si_ra1.append(s) si_ra = numpy.mean(si_ra1) si_ra_list.append(si_ra) print si_ra_list
when ran script gave me error: line 73: list index out of range.
know error be? sorry long script. don't know how shorten yet.
on line 65, change condition to:
elif r > (len(table) - 5):
the problem iterate towards end of list on line 73, trying next 5 datapoints in list, there 4 datapoints left in list, indexing beyond length of list, hence exception thrown.
Comments
Post a Comment