Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Average every x numbers in NumPy array

Let's say I have an array of 100 random numbers called random_array. I need to create an array that averages x numbers in random_array and stores them.

So if I had x = 7, then my code finds the average of the first 7 numbers and stores them in my new array, then next 7, then next 7...

I currently have this but I'm wondering how I can vectorize it or use some python method:

random_array = np.random.randint(100, size=(100, 1))
count = 0
total = 0
new_array = []
for item in random_array:
    if (count == 7):
        new_array.append(total/7)
        count = 0
        total = 0
    else:
        count = count + 1
        total = total + item
print new_array
like image 842
user1883614 Avatar asked Mar 15 '26 07:03

user1883614


1 Answers

Here's the standard trick

def down_sample(x, f=7):
    # pad to a multiple of f, so we can reshape
    # use nan for padding, so we needn't worry about denominator in
    # last chunk
    xp = np.r_[x, nan + np.zeros((-len(x) % f,))]
    # reshape, so each chunk gets its own row, and then take mean
    return np.nanmean(xp.reshape(-1, f), axis=-1)
like image 181
Paul Panzer Avatar answered Mar 17 '26 21:03

Paul Panzer