BenL - 10 months ago 46

Python Question

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!

Answer

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
```

Source (Stackoverflow)