有效地减去不同形状的numpy数组

时间:2020-11-30 21:24:53

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

使用numpy的优秀广播规则,您可以从形状(5,3)数组X中减去形状(3,)数组v

X - v

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

结果是形状(5,3)数组,其中每行i是差X [i] -v。

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中减去一个形状(n,3)数组w,以便从整个数组X中减去w的每一行而不显式使用循环?

1 个解决方案

#1


8  

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 -

您需要使用None / np.newaxis扩展X的尺寸以形成3D数组,然后通过w进行减法。这将为该3D操作带来广播,并产生形状为(5,n,3)的输出。实现看起来像这样 -

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

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

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

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

Sample run -

样品运行 -

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)

#1


8  

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 -

您需要使用None / np.newaxis扩展X的尺寸以形成3D数组,然后通过w进行减法。这将为该3D操作带来广播,并产生形状为(5,n,3)的输出。实现看起来像这样 -

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

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

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

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

Sample run -

样品运行 -

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)