简体   繁体   中英

Using python for loop to average data

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!

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM