Reputation: 42329
This is a rather simple question but I can't seem to find the answer. Consider two simple arrays:
import numpy as np
a = np.random.uniform(0., 1., (2, 1000))
b = np.random.uniform(0., 1., (2,))
I want to perform the operation a - b
so that the final array is ([[a[0] - b[0], a[1] - b[1]])
and I get
ValueError: operands could not be broadcast together with shapes (2,1000) (2,)
How can I perform this (or some other) operation?
Upvotes: 0
Views: 234
Reputation: 214927
According to the General Broadcasting Rules:
When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing dimensions, and works its way forward. Two dimensions are compatible when
- they are equal, or
- one of them is 1
So there's the error because the last dimension of a
(1000) and b
(2) can not be broadcasted; You can convert b
to a 2d array of shape (2, 1)
so that 1
-> (can broadcast to) 1000
, 2
-> (can broadcast to) 2
:
a - b[:,None]
#array([[ 0.06475683, -0.43773571, -0.62561564, ..., 0.05205518,
# -0.1209487 , 0.16334639],
# [ 0.58443617, 0.28764136, 0.75789299, ..., 0.18159133,
# 0.28548633, -0.12037869]])
Or
a - b.reshape(2,1)
Upvotes: 2