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

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

问题描述

使用的numpy的,你可以减去一个形状(3)阵列 v 从形状(5,3)阵列 X中的优秀广播规则

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

有没有办法减去形状(N,3)阵列是W X 使每一行是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?

推荐答案

您需要 X 的尺寸用的 无/ np.newaxis 形成一个三维数组,然后通过做减法是W 。这将带来 广播 进入这个 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天全站免登陆