Numpy subtract / add 1d array from 2d array

I have the following 2D array:

a = array([[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9], [10, 11, 12], [13, 14, 15]]) 

and another 1D array:

 b = array([ 1, 2, 3, 4, 5]) 

then I want to calculate something like

 c = a - b 

in order to obtain:

 c = array([[0, 1, 2], [2, 3, 4], [4, 5, 6], [6, 7, 8], [8, 9, 10]]) 

but instead I get an error:

 Traceback (most recent call last): Python Shell, prompt 79, line 1 ValueError: operands could not be broadcast together with shapes (5,3) (5,) 

I read the broadcast rules, but did not become wiser. I could make a workaround with for-loops or similar, but there should be a straight path. Thanks

+5
source share
2 answers

You need to convert the array b to a (2, 1) shape , use None or numpy.newaxis in the index tuple. Here is the Numpy Array Indexing .

You can do it like:

 import numpy a = numpy.array([[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9], [10, 11, 12], [13, 14, 15]]) b = numpy.array([ 1, 2, 3, 4, 5]) c=a - b[:,None] print c 

Output:

 Out[2]: array([[ 0, 1, 2], [ 2, 3, 4], [ 4, 5, 6], [ 6, 7, 8], [ 8, 9, 10]]) 
+13
source

As stated in the Divakar comments, just add a new axis to b .

I suggest you learn more about broadcasting , which is very useful for vectorizing computations in numpy: interestingly enough, a.transpose() - b wouldn’t cause an error (you would need to transpose the result again to get the desired result).

In this calculation, the first form of the array is (3, 5) , and b.shape is (5). Thus, form b corresponds to the tail of form a , and broadcasting may occur. This is not the case when the shape of the first array (5, 3) , therefore, the error you received.

Below are some runtime tests to compare the suggested response rates with your values ​​for a and b : you can see that the differences are not very significant

 In [9]: %timeit (aT - b).T Out[9]: 1000000 loops, best of 3: 1.32 µs per loop In [10]: %timeit a - b[:,None] Out[10]: 1000000 loops, best of 3: 1.25 µs per loop In [11]: %timeit a - b[None].T Out[11]: 1000000 loops, best of 3: 1.3 µs per loop 
+2
source

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


All Articles