Dawn17
Dawn17

Reputation: 8297

How do I do a column-wise subtraction using numpy?

Let's say I have:

array([[ 5,  4,  3,  3],
       [ 5,  4,  3,  3],
       [ 5,  4,  3,  3],
       [ 5,  4,  3,  3],
       [ 5,  4,  3,  3]])

And then I have

array([1, 2, 3, 4])

I want to subtract each column in the original matrix with the corresponding column value in the 1d array.

So, I want it to become

array([[ 4,  2,  0,  -1],
       [ 4,  2,  0,  -1],
       [ 4,  2,  0,  -1],
       [ 4,  2,  0,  -1],
       [ 4,  2,  0,  -1]])

How can this be achieved in numpy?

Upvotes: 1

Views: 107

Answers (1)

iz_
iz_

Reputation: 16593

It's much easier than you think:

In [1]: import numpy as np

In [2]: arr = np.array([[ 5,  4,  3,  3],
    ...:                [ 5,  4,  3,  3],
    ...:                [ 5,  4,  3,  3],
    ...:                [ 5,  4,  3,  3],
    ...:                [ 5,  4,  3,  3]])

In [3]: sub = np.array([1, 2, 3, 4])

In [4]: arr - sub
Out[4]:
array([[ 4,  2,  0, -1],
       [ 4,  2,  0, -1],
       [ 4,  2,  0, -1],
       [ 4,  2,  0, -1],
       [ 4,  2,  0, -1]])

NumPy broadcasts automatically, so just use the - operator!

Upvotes: 2

Related Questions