Numpy: Subtract 2 numpy arrays row wise

前端 未结 4 1092
被撕碎了的回忆
被撕碎了的回忆 2021-01-14 05:51

I have 2 numpy arrays a and b as below:

a = np.random.randint(0,10,(3,2))
Out[124]: 
array([[0, 2],
       [6, 8],
       [0, 4]])
b = np.random.randint(0,10         


        
4条回答
  •  说谎
    说谎 (楼主)
    2021-01-14 06:06

    Just use np.newaxis (which is just an alias for None) to add a singleton dimension to a, and let broadcasting do the rest:

    In [45]: a[:, np.newaxis] - b
    Out[45]: 
    array([[[-5, -7],
            [-2, -2]],
    
           [[ 1, -1],
            [ 4,  4]],
    
           [[-5, -5],
            [-2,  0]]])
    

提交回复
热议问题