Efficient subtraction of numpy arrays of various shapes

Using the excellent numpy broadcast rules, you can subtract an array of form (3,) vfrom an array of form (5.3) Xwith

X - v

The result is an array of form (5.3), in which each row iis a difference X[i] - v.

Is there a way to subtract an array of form (n, 3) wfrom Xso that each row is wsubtracted from the whole array Xwithout explicitly using a loop?

+4
source share
1 answer

X None/np.newaxis, 3D-, w. broadcasting 3D (5,n,3). :

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

, (n,5,3), w, :

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)
+6

Source: https://habr.com/ru/post/1615624/