Spencer Hill - 1 year ago 92

Python Question

I have a numpy array,

`a`

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

`a`

`b`

`b.shape=(90,144)`

`(48,)`

I know this can be done with a list comprehension:

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

But I'd like to avoid having to convert from a list back to a numpy array.

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

Answer Source

In a single 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)]))
```