Average values in two Numpy arrays
Using numpy.average
Also numpy.average
can be used with the same syntax:
import numpy as np
a = np.array([np.arange(0,9).reshape(3,3),np.arange(9,18).reshape(3,3)])
averaged_array = np.average(a,axis=0)
The advantage of numpy.average compared to numpy.mean
is the possibility to use also the weights parameter as an array of the same shape:
weighta = np.empty((3,3))
weightb = np.empty((3,3))
weights = np.array([weighta.fill(0.5),weightb.fill(0.8) ])
np.average(a,axis=0,weights=weights)
If you use masked arrays consider also using numpy.ma.average
because numpy.average
don't deal with them.
You can create a 3D array containing your 2D arrays to be averaged, then average along axis=0
using np.mean
or np.average
(the latter allows for weighted averages):
np.mean( np.array([ old_set, new_set ]), axis=0 )
This averaging scheme can be applied to any (n)
-dimensional array, because the created (n+1)
-dimensional array will always contain the original arrays to be averaged along its axis=0
.
>>> import numpy as np
>>> old_set = [[0, 1], [4, 5]]
>>> new_set = [[2, 7], [0, 1]]
>>> (np.array(old_set) + np.array(new_set)) / 2.0
array([[1., 4.],
[2., 3.]])