Numpy: Subtract 2 numpy arrays row wise

前端 未结 4 1095
被撕碎了的回忆
被撕碎了的回忆 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:24

    Reading from the doc on broadcasting, it says:

    When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing dimensions, and works its way forward. Two dimensions are compatible when

    they are equal, or
    one of them is 1
    

    Back to your case, you want result to be of shape (3, 2, 2), following these rules, you have to play around with your dimensions. Here's now the code to do it:

    In [1]: a_ = np.expand_dims(a, axis=0)
    
    In [2]: b_ = np.expand_dims(b, axis=1)
    
    In [3]: c = a_ - b_
    
    In [4]: c
    Out[4]: 
    array([[[-5, -7],
            [ 1, -1],
            [-5, -5]],
    
           [[-2, -2],
            [ 4,  4],
            [-2,  0]]])
    
    In [5]: result = c.swapaxes(1, 0)
    
    In [6]: result
    Out[6]: 
    array([[[-5, -7],
            [-2, -2]],
    
           [[ 1, -1],
            [ 4,  4]],
    
           [[-5, -5],
            [-2,  0]]])
    
    In [7]: result.shape
    Out[7]: (3, 2, 2)
    

提交回复
热议问题