numpy: multiply arrays rowwise

Question:

I have those arrays:

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

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

and I want them to multiply like so:

[[1*1, 2*1],
[3*2, 4*2],
[5*3, 6*3],
[7*4, 8*4]]

… basically out[i] = a[i] * b[i], where a[i].shape is (2,) and b[i] then is a scalar.

What’s the trick? np.multiply seems not to work:

>>> np.multiply(a, b)
ValueError: operands could not be broadcast together with shapes (4,2) (4)
Asked By: wal-o-mat

||

Answers:

add an axis to b:

>>> np.multiply(a, b[:, np.newaxis])
array([[ 1,  2],
       [ 6,  8],
       [15, 18],
       [28, 32]])
Answered By: behzad.nouri
>>> a * b.reshape(-1, 1)
array([[ 1,  2],
       [ 6,  8],
       [15, 18],
       [28, 32]])
Answered By: Vladimir Iashin

For those who don’t want to use np.newaxis or reshape, this is as simple as:

a * b[:, None]

This is because np.newaxis is actually an alias for None.

Read more here.

Answered By: Austin

It looks nice, but quite naive, I think, because if you change the dimensions of a or b, the solution

np.mulitply(a, b[:, None])

doesn’t work anymore.

I’ve always had the same doubt about multiplying arrays of arbitrary size row rise, or even, more generally, n-th dimension wise.

I used to do something like

 z = np.array([np.multiply(a, b) for a, b in zip(x,y)])

and that works for x or y that have dimension 1 or 2.

Does it exist with a method with “axis” argument like in other numpy methods? Such like

 z = np.mulitply(x, y, axis=0)
Answered By: Alexandre

What’s missing here is the einsum (doc) variant:

np.einsum("ij,i->ij", a, b)

This gives you full control over the indices and a and b are passed blank.

Answered By: greeeeeeen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.