I have the following 2D-array:
a = array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12],
[13, 14, 15]])
As Divakar specified in the comments, just add a new axis to b
.
I suggest you read more about broadcasting which is very often useful to vectorize computations in numpy: interestingly enough, a.transpose() - b
wouldn't have raised an error (you'd need to transpose the result again to obtain your desired output).
In this computaion, the first array's shape is (3, 5)
, and b.shape
is (5,). So the shape of b
corresponds to the tail of the shape of a
, and broadcasting can happen. This is not the case when the shape of the first array is (5, 3)
, hence the error you obtained.
Here are some runtime tests to compare the speeds of the suggested answers, with your values for a
and b
: you can see that the differences are not really significant
In [9]: %timeit (a.T - 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