有效地减去不同形状的 numpy 数组 [英] Subtracting numpy arrays of different shape efficiently

查看:28
本文介绍了有效地减去不同形状的 numpy 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 numpy 的优秀广播规则,您可以使用

Using the excellent broadcasting rules of numpy you can subtract a shape (3,) array v from a shape (5,3) array X with

X - v

结果是一个形状为 (5,3) 的数组,其中每一行 i 是差值 X[i] - v.

The result is a shape (5,3) array in which each row i is the difference X[i] - v.

有没有办法从 X 中减去一个形状 (n,3) 数组 w 以便 w 的每一行都减去形式整个数组 X 没有显式使用循环?

Is there a way to subtract a shape (n,3) array w from X so that each row of w is subtracted form the whole array X without explicitly using a loop?

推荐答案

您需要使用 None/np.newaxis 组成一个3D数组,然后用w做减法.这会将 broadcasting 引入播放此 3D 操作并产生形状为 (5,n,3) 的输出.实现看起来像这样 -

You need to extend the dimensions of X with None/np.newaxis to form a 3D array and then do subtraction by w. This would bring in broadcasting into play for this 3D operation and result in an output with a shape of (5,n,3). The implementation would look like this -

X[:,None] - w  # or X[:,np.newaxis] - w

相反,如果所需的排序是 (n,5,3),那么您需要扩展 w 的维度,就像这样 -

Instead, if the desired ordering is (n,5,3), then you need to extend the dimensions of w instead, like so -

X - w[:,None] # or X - w[:,np.newaxis] 

样品运行 -

In [39]: X
Out[39]: 
array([[5, 5, 4],
       [8, 1, 8],
       [0, 1, 5],
       [0, 3, 1],
       [6, 2, 5]])

In [40]: w
Out[40]: 
array([[8, 5, 1],
       [7, 8, 6]])

In [41]: (X[:,None] - w).shape
Out[41]: (5, 2, 3)

In [42]: (X - w[:,None]).shape
Out[42]: (2, 5, 3)

这篇关于有效地减去不同形状的 numpy 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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