(This question is similar to Numpy averaging with multi-dimensional weights along an axis, but more complicated.)
I have a numpy array, d, d.shape=(16,3,90,144), and a numpy array of weights, e, e.shape=(16,3). I want to take a weighted average of a along axis 1 using e. So the output should be a numpy array with shape (16,90,144). I can accomplish this with a list comprehension:
np.array([np.average(d[n], weights=e[n], axis=0) for n in range(16)])
But as in the previous question, I would like to avoid having to convert from a list back to a numpy array. This case is more complicated than the previous question because the weights aren’t the same each time (i.e. weights=e[n], not weights=b).
Can anybody help? Thanks!
It would be nice to use
np.averagedirectly. However, to do so,dand the weightsewould have to have the same shape, and broadcasting is not done implicitly for you here.Explicitly broadcasting
e(usingnp.broadcast_arrays) so it has same shape asdis possible, but a waste of memory. So instead of doing that, would could a peek at the source code defining numpy.average and try to reproduce the calculation:Here is a check that the calculation returns the same result as the list comprehension: