2

Is it possible to divide multiple numpy array columns by another 1D column (row wise division)?

Example:

a1 = np.array([[1,2,3],[4,5,6],[7,8,9]])
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
a2 = np.array([11,12,13])
array([11, 12, 13])
# that is divide all rows, but only columns 1 and 2 by a2 array
a1[:,:2] / a2
ValueError: operands could not be broadcast together with shapes (3,2) (3,)

I did try this, but this does not look elegant

(a1[:,:2].T / a2).T
array([[0.09090909, 0.18181818],
       [0.33333333, 0.41666667],
       [0.53846154, 0.61538462]])
4
  • So, what would the right answer be for your sample data? Commented Aug 28, 2022 at 5:38
  • 1
    Did you mean something like this a1[:,:2] / a2[:2]? Commented Aug 28, 2022 at 5:40
  • Hey Soroush i did and just realize that was also the issue, but i did need column wise which i thought the double transpose was crummy Commented Aug 28, 2022 at 5:41
  • By the rules of broadcasting the second array needs to be (3,1) shape. The default expansion to 2d is (1,3), which is not what you want. Commented Aug 28, 2022 at 16:11

1 Answer 1

2

Your a1 array is 2D and a2 is 1D, try expanding the dimension of a2 array to 2D before performing division:

>>> a1[:,:2]/np.expand_dims(a2, 1)

array([[0.09090909, 0.18181818],
       [0.33333333, 0.41666667],
       [0.53846154, 0.61538462]])

Apparently, you can just use a2[:, None] instead of calling expand_dims function for even cleaner code.

Sign up to request clarification or add additional context in comments.

5 Comments

Another way to do expand_dims is by adding None to a slice: a2[:,None].
@Blckknght, yes but it may not be explicitly clear for those who are just getting started with numpy.
I agree, explicit is often better!
awesome, thanks. I'll accept this once the 5min countdown is done :)
oh @Blckknght i really like your answer, that to me is pretty clear since all i do is slice

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.