Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting numpy arrays of different shape efficiently

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

The result is a shape (5,3) array in which each row i is the difference 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?

like image 420
MaxPowers Avatar asked Nov 12 '15 17:11

MaxPowers


People also ask

How do you subtract two NumPy arrays of different sizes?

The most straightforward way to subtract two matrices in NumPy is by using the - operator, which is the simplification of the np. subtract() method - NumPy specific method designed for subtracting arrays and other array-like objects such as matrices.

Can you subtract NumPy arrays?

A Quick Introduction to Numpy SubtractWhen you use np. subtract on two same-sized Numpy arrays, the function will subtract the elements of the second array from the elements of the first array. It performs this subtraction in an “element-wise” fashion.

Which NumPy method is used to change the shape of array?

Reshaping means changing the shape of an array. The shape of an array is the number of elements in each dimension. By reshaping we can add or remove dimensions or change number of elements in each dimension.


1 Answers

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

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] 

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)
like image 162
Divakar Avatar answered Sep 23 '22 22:09

Divakar