0

I have two numpy arrays

a = numpy.array([1, 0])
b = numpy.array([[0.2, 0.4, 0.1],
                 [0.8, 0.5, 0.3]])

I want to subtract b from a.

If I write a[0] - b[0] I get [0.8, 0.6, 0.9]

If I write a[1] - b[1] I get [-0.8, -0.5, -0.3]

Subtraction between these arrays is obviously possible, but if I write a - b, I get this:

ValueError: operands could not be broadcast together with shapes (2,) (2,3)

Why is this not possible?

Jonas
  • 19
  • 4
  • Have you read in the basic `numpy` docs about `broadcasting`? The arrays do have different shapes. – hpaulj Mar 18 '21 at 18:24
  • 1
    `(2,) (2,3)` are non-broadcast able shapes. Reshape `a` to `(2,1)` and it should work. Just add `a = numpy.reshape(a, (2,1))` – Ayush Shridhar Mar 18 '21 at 18:25
  • You could do `(a - b.T).T`. More compact than the answer above, but I would use the answer above as it's a bit clearer IMO. – Xirtaminu Mar 21 '21 at 19:57

0 Answers0