Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decrease array size by averaging adjacent values with numpy

I have a large array of thousands of vals in numpy. I want to decrease its size by averaging adjacent values. For example:

a = [2,3,4,8,9,10]
#average down to 2 values here
a = [3,9]
#it averaged 2,3,4 and 8,9,10 together

So, basically, I have n number of elements in array, and I want to tell it to average down to X number of values, and it averages like above.

Is there some way to do that with numpy (already using it for other things, so I'd like to stick with it).

like image 846
Adam Haile Avatar asked Oct 29 '14 18:10

Adam Haile


1 Answers

Using reshape and mean, you can average every m adjacent values of an 1D-array of size N*m, with N being any positive integer number. For example:

import numpy as np

m = 3
a = np.array([2, 3, 4, 8, 9, 10])
b = a.reshape(-1, m).mean(axis=1)
#array([3., 9.])

1)a.reshape(-1, m) will create a 2D image of the array without copying data:

array([[ 2,  3,  4],
       [ 8,  9, 10]])

2)taking the mean in the second axis (axis=1) will then calculate the mean value of each row, resulting in array([3., 9.]).

like image 186
Saullo G. P. Castro Avatar answered Sep 22 '22 04:09

Saullo G. P. Castro