Advertisement
Advertisement


Generalizing a method in Python


Question

I'm trying to create a method that an array I have of wind and demand averages through out the day in 15 minute intervals for 1 year. I want to turn this into a daily average for each of the 365 days. Here's what I have so far:

dailyAvg = []   # this creates the initial empty array for method below
def createDailyAvg(p):  # The method
    i = 0
    while i < 35140:    # I have 35140 data points in my array
        dailyAvg.append(np.mean(p[i:i+95]))  #Creates the avg of the 96, 15 minute avg
        i += 95
    return dailyAvg 

dailyAvgWind = createDailyAvg(Wind) # Wind is the array of 15 minute avg's.
dailyAvgDemand = createDailyAvg(M) # M is the array of demand avg's

So far I can get this done if I write this twice, but that's not good programming. I want to figure out how I can use this one method on both data sets. Thanks.

2013/08/27
1
2
8/27/2013 2:18:05 AM

Accepted Answer

You just need to make dailyAvg local to the function. This way, it will be initialized to an empty list every time the function executes (I bet the problem was that the function's result grew and grew and grew, appending the new averages, but not deleting the previous ones)

def createDailyAvg(p):  # The method
    dailyAvg = []   # this creates the initial empty array for this method below
    i = 0
    while i < 35140:    # I have 35140 data points in my array
        dailyAvg.append(np.mean(p[i:i+96]))  #Creates the avg of the 96, 15 minute avg
        i += 96
    return dailyAvg 

dailyAvgWind = createDailyAvg(Wind) # Wind is the array of 15 minute avg's.
dailyAvgDemand = createDailyAvg(M) # M is the array of demand avg's

Also, I replaced 95 with 96 in two places, as the end of a slice excludes the specified end.

2013/08/27
4
8/27/2013 4:02:27 AM

def createDailyAvg(w,m):  # The method
    dailyAvg = [[],[]]   # this creates the initial empty array for method below
    i = 0
    while i < 35140:    # I have 35140 data points in my array
        dailyAvg[0].append(np.mean(w[i:i+95]))  #Creates the avg of the 96, 15 minute avg
        dailyAvg[1].append(np.mean(m[i:i+95]))
        i += 95
    return dailyAvg 
dailyAvg = createDailyAvg(Wind,M)
dailyAvgWind = dailyAvg[0] # Wind is the array of 15 minute avg's.
dailyAvgDemand = dailyAvg[1] # M is the array of demand avg's
2013/08/27