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?

gabboshow
  • 5,359
  • 12
  • 48
  • 98

3 Answers3

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]])
MB-F
  • 22,770
  • 4
  • 61
  • 116
0

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

a - b[:, np.newaxis]
pstjohn
  • 521
  • 5
  • 13
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.

Community
  • 1
  • 1
Jonathan Eunice
  • 21,653
  • 6
  • 75
  • 77
  • 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 '17 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. – Jonathan Eunice Mar 15 '17 at 21:26