Subtract a column vector from matrix at specified vector of columns using only broadcast

后端 未结 2 1160
余生分开走
余生分开走 2021-01-19 08:10

I want to subtract a column vector from a numpy matrix using another vector which is index of columns where the first column vector needs to be subtracted from the main mat

相关标签:
2条回答
  • 2021-01-19 08:33

    We can use np.subtract.at on transposed view of M -

    np.subtract.at(M.T,I,V)
    
    0 讨论(0)
  • 2021-01-19 08:35

    One can use bincount and outer

    >>> M - np.outer(V, np.bincount(I, None, M.shape[1]))
    array([[ 0,  1,  0, -3],
           [ 1,  0,  0, -3],
           [ 0,  0,  1, -3],
           [ 1,  0,  0, -3],
           [ 0,  0,  0, -2]])
    

    or subtract.at

    >>> out = M.copy()
    >>> np.subtract.at(out, (np.s_[:], I), V[:, None])
    >>> out
    array([[ 0,  1,  0, -3],
           [ 1,  0,  0, -3],
           [ 0,  0,  1, -3],
           [ 1,  0,  0, -3],
           [ 0,  0,  0, -2]])
    
    0 讨论(0)
提交回复
热议问题