0

I have two numpy array a and b

a=np.array([[1,2,3],[4,5,6],[7,8,9]])
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

b = np.array([1,2,3])
array([1, 2, 3])

I would like to substract to each row of a the correspondent element of b (ie. to the first row of a, the first element of b, etc) so that c is

array([[0, 1, 2],
       [2, 3, 4],
       [4, 5, 6]])

Is there a python command to do this?

1
  • your question is entirely answered by the top two responses in the marked duplicate. Mar 15, 2017 at 16:17

3 Answers 3

1

Is there a python command to do this?

Yes, the - operator.

In addition you need to make b into a column vector so that broadcasting can do the rest for you:

a - b[:, np.newaxis]

# array([[0, 1, 2],
#        [2, 3, 4],
#        [4, 5, 6]])
0

yup! You just need to make b a column vector first

a - b[:, np.newaxis]
0

Reshape b into a column vector, then subtract:

a - b.reshape(3, 1)

b isn't altered in place, but the result of the reshape method call will be the column vector:

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

Allowing the "shape" of the subtraction you wanted. A little more general reshape operation would be:

b.reshape(b.size, 1)

Taking however many elements b has, and molding them into an N x 1 vector.

Update: A quick benchmark shows kazemakase's answer, using b[:, np.newaxis] as the reshaping strategy, to be ~7% faster. For small vectors, those few extra fractions of a µs won't matter. But for large vectors or inner loops, prefer his approach. It's a less-general reshape, but more performant for this use.

2
  • Small addendum to the general reshaping: b.reshape(-1, 1) lets reshape set the size of one dimension automatically without explicitly querying b.shape.
    – MB-F
    Mar 15, 2017 at 19:22
  • @kazemakase Good point. Wasn't sure OP was ready to take on the -1 wildcard, but since you bring it up, it tunes performance with no loss of generality. Thumbs up. Mar 15, 2017 at 21:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.