Reputation: 173
I have a data set that contains 20 years of monthly averages in a numpy array with dimensions (1x240). I'm trying to write a function to spit out the yearly averages. I've managed to do it (I believe), using a for loop, but when I stick the exact same code into a function, it only gives me the first of what should be 20 values.
def yearlymean_gm(gm_data):
data= np.load(gm_data)
for i in range (0,20):
average= data[i*12:i*12+12].sum()/12
print average
return average
gm_data is the name of the file.
When I simply manually enter
data= np.load(gm_data)
for i in range (0,20):
average= data[i*12:i*12+12].sum()/12
print average
return average
it successfully reads out the 20 values. I'm pretty sure I just don't quite understand how for loops work in the context of functions. Any explanation (and a fix, if possible), would be awesome.
Secondly, I would love to have these values fed into an numpy array. I tried
def yearlymean_gm(gm_data):
data= np.load(gm_data)
average = np.zeroes(20)
for i in range (0,20):
average[i]= data[i*12:i*12+12].sum()/12
print average
return average
but this gives me a long, wacky, list. Help on this would be cool too. Thanks!
Upvotes: 0
Views: 4683
Reputation: 1082
Why not avoid the "for" loop altogether?
def yearlymean_gm(gm_data):
data = np.load(gm_data)
data = data.reshape((12, 20))
print data.mean(axis=1)
return data.mean(axis=1)
Upvotes: 5
Reputation: 11075
here's what you need...
def yearlymean_gm(gm_data):
data= np.load(gm_data)
average = np.zeroes(20)
for i in range (0,20):
average[i]= data[i*12:i*12+12].sum()/12
print average
return average #don't return until the loop has completed
Upvotes: 1