Swap zeros in numpy matrix

后端 未结 6 1164
眼角桃花
眼角桃花 2021-01-20 13:08

I have a numpy matrix like so:

array([[2,  1, 23, 32],
       [34, 3, 3, 0],
       [3, 33, 0, 0],
       [32, 0, 0, 0]], dtype=int32)

Now

6条回答
  •  情歌与酒
    2021-01-20 13:55

    You can also perform sorting on the masked array with the help of numpy.ma.sort() that sorts the array in-place along the last axis, axis=-1 as shown:

    np.ma.array(a, mask=a!=0).sort()
    

    Now a becomes:

    array([[ 2,  1, 23, 32],
           [ 0, 34,  3,  3],
           [ 0,  0,  3, 33],
           [ 0,  0,  0, 32]])
    

    The only downside is that it is not as fast as some of the approaches mentioned above but nevertheless a short one-liner to have.

提交回复
热议问题