1

I have two 2D numpy arrays. I want to add a slice of the array via broadcasting:

a = np.zeros((3,5))
b = np.zeros((3,5))

c = a + b[0,:]  # Works fine
c = a + b[:,0]  # -> ValueError: operands could not be broadcast together with shapes (3,5) (3,) 

The problem is, that b[:,0] creates a 1D array which is not properly broadcasted to a.

Is there an easy way to add 2D and 1D arrays?

twiine
  • 21
  • 2
  • 1
    `a + b[:, :1]` or `a + b[:, 0, None]` – Mechanic Pig Sep 10 '22 at 16:46
  • 1
    yes, the key is that the `b` slice needs to be (3,1) shaped. There are various ways of doing that. With `b[0,:]` the shape is (5,), which automatically is expanded to (1,5) (1st step of broadcasting). Adding a trailing dimension has to be explicit. – hpaulj Sep 10 '22 at 17:02

0 Answers0