Numerical averaging with multivariate weights along the axis

I have an array numpy, a

, a.shape=(48,90,144)

. I want to take a weighted average of a

a first axis, using scales in the array b

, b.shape=(90,144)

. Thus, the output must be massive in size (48,)

.

I know it can be done with a list:

np.array([np.average(a[i], weights=b) for i in range(48)])

      

But I wish you didn't have to convert from the list back to a numpy array.

Can anyone please help? I'm sure this is possible using numpy functions and slicing, but I am stuck. Thank!

+3


source to share


2 answers


In one line:

np.average(a.reshape(48, -1), weights=b.ravel()), axis=1)

      



You can test it with:

a = np.random.rand(48, 90, 144)
b = np.random.rand(90,144)
np.testing.assert_almost_equal(np.average(a.reshape(48, -1),
                                          weights=b.ravel(), axis=1),
                               np.array([np.average(a[i],
                                                    weights=b) for i in range(48)]))

      

+5


source


This was the post I could come up with:

(a * b).mean(-1).mean(-1) * (b.size / b.sum())

      

It can be suitable for any number of starting and ending measurements.



Reform and 1 x average did not accelerate:

(a * b).reshape(len(a), -1).mean(-1) * (b.size / b.sum())

      

0


source







All Articles