Home > other >  numpy array divide multiple columns by one column
numpy array divide multiple columns by one column

Time:08-28

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]])

CodePudding user response:

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.

  • Related