Skip to content
Advertisement

How to add elements of a 1D NumPy array to NumPy subarrays with the same index?

Let’s say I have a NumPy array a with shape (3, 5, 7) and a 1D NumPy array l with shape (3, 1). I want to add the 0th element of l to the 0th subarray in a, the 1st element of l to the 1st subarray of a, and the 2nd element of l to the 2nd and last subarray of a.

For instance, if l = [[30 40 50]], then I want a[0] += 30, a[1] += 40, a[2] += 50.

I know that to achieve this, I can easily do the following:

JavaScript

but I was wondering if there’s a way to do this with pure NumPy, no for loops required. Trying np.add(a, l) invariably creates the error operands could not be broadcast together with shapes (3,5,7) (3,1) and trying the following:

JavaScript

gives me a final shape of (3, 3, 5, 7), which is not what I want. Thanks for your help!

EDIT: I figured it out:

JavaScript

Advertisement

Answer

JavaScript

That leading 1 dimension doesn’t help; you have to transpose anyways

JavaScript

The broadcasting works fine if b is (3,1,1) shape:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement