average numpy array but retain shape average numpy array but retain shape numpy numpy

average numpy array but retain shape


Ok, CAUTION I don't have my masters in numpyology yet, but just playing around, I came up with:

>>> np.average(a,axis=-1).repeat(a.shape[-1]).reshape(a.shape)array([[[ 0.2       ,  0.2       ,  0.2       ],        [ 0.29999998,  0.29999998,  0.29999998]],       [[ 0.40000001,  0.40000001,  0.40000001],        [ 0.69999999,  0.69999999,  0.69999999]]], dtype=float32)


Have you considered using broadcasting? Here is more info about broadcasting if you're new to the concept.

Here is an example using broadcast_arrays, keep in mind that the b produced here by broadcast_arrays should be treated as read only, you should make a copy if you want to write to it:

>>> b = np.average(a, axis=2)[:, :, np.newaxis]>>> b, _ = np.broadcast_arrays(b, a)>>> barray([[[ 0.2       ,  0.2       ,  0.2       ],        [ 0.29999998,  0.29999998,  0.29999998]],       [[ 0.40000001,  0.40000001,  0.40000001],        [ 0.69999999,  0.69999999,  0.69999999]]], dtype=float32)


>>> import numpy as np>>> a = np.array([[[0.1, 0.2, 0.3], [0.2, 0.3, 0.4]],...               [[0.4, 0.4, 0.4], [0.7, 0.6, 0.8]]], np.float32)>>> b = np.average(a, axis=2)>>> barray([[ 0.2       ,  0.29999998],       [ 0.40000001,  0.69999999]], dtype=float32)>>> c = np.dstack((b, b, b))>>> carray([[[ 0.2       ,  0.2       ,  0.2       ],        [ 0.29999998,  0.29999998,  0.29999998]],       [[ 0.40000001,  0.40000001,  0.40000001],        [ 0.69999999,  0.69999999,  0.69999999]]], dtype=float32)