沿轴进行多维权重的Numpy平均 [英] Numpy averaging with multi-dimensional weights along an axis

查看:104
本文介绍了沿轴进行多维权重的Numpy平均的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个numpy数组aa.shape=(48,90,144).我想使用数组bb.shape=(90,144)中的权重沿第一个轴获取a的加权平均值.因此,输出应该是形状为(48,)的numpy数组.

I have a numpy array, a, a.shape=(48,90,144). I want to take the weighted average of a along the first axis using the weights in array b, b.shape=(90,144). So the output should be a numpy array of shape (48,).

我知道可以通过列表理解来完成:

I know this can be done with a list comprehension:

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

但是我想避免不得不从列表转换回numpy数组.

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

任何人都可以帮忙吗?我确定使用numpy函数和切片是可能的,但是我被卡住了.谢谢!

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

推荐答案

一行:

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)]))

这篇关于沿轴进行多维权重的Numpy平均的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆