Reputation: 431
I would like to compute the element-wise mean of elements in a 1D array.
>>> a = np.array([1, 3, 5, 7])
>>> b = element_wise_mean(a)
>>> b
array([2., 4., 6.])
Is there anything that will already do this other than a simple custom function?
Upvotes: 0
Views: 320
Reputation: 3776
Use the following code:
>>> (a[:-1]+a[1:])/2
array([ 2., 4., 6.])
The following steps are taken:
>>> a[:-1]
array([1, 3, 5])
>>> a[1:]
array([3, 5, 7])
>>> a[:-1]+a[1:]
array([ 4, 8, 12])
>>> (a[:-1]+a[1:])/2
array([ 2., 4., 6.])
A more generic way would be to have a moving average filter over N
elements (code is taken from lapis with addition from Paul Panzer). In your case it would be averaging over two elements:
>>> N=2
>>> np.convolve(a, np.ones((N,))/N, mode='valid')
array([ 2., 4., 6.])
>>> N=3
>>> np.convolve(a, np.ones((N,))/N, mode='valid')
array([ 3., 5.])
Upvotes: 4