Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

numpy array divide multiple columns by one column

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(a1[:,:2].T / a2).T
array([[0.09090909, 0.18181818],
       [0.33333333, 0.41666667],
       [0.53846154, 0.61538462]])

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading