0

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?

mitchute
  • 389
  • 1
  • 3
  • 10
  • can you be more explicity? you have an array of 4 elements and you expect an array of 4 elements as output. what is for you element-wiseness? – asdf Apr 04 '18 at 22:50
  • For an N-element array, I expect an N-1 array to be returned as shown. – mitchute Apr 04 '18 at 22:58

1 Answers1

4

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.])
Günther Jena
  • 3,706
  • 3
  • 34
  • 49