Reputation: 7344
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)
Upvotes: 44
Views: 42514
Reputation: 678
This is how a*b works when a is transposed so you can also do
np.transpose(np.transpose(a)*b)
Upvotes: 0
Reputation: 859
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.
Upvotes: 7
Reputation: 12
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)
Upvotes: -2
Reputation: 26039
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.
Upvotes: 21
Reputation: 793
>>> a * b.reshape(-1, 1)
array([[ 1, 2],
[ 6, 8],
[15, 18],
[28, 32]])
Upvotes: 12
Reputation: 77951
add an axis to b:
>>> np.multiply(a, b[:, np.newaxis])
array([[ 1, 2],
[ 6, 8],
[15, 18],
[28, 32]])
Upvotes: 54