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

后端 未结 2 1173
余生分开走
余生分开走 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: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]])
    

提交回复
热议问题