Swap zeros in numpy matrix

后端 未结 6 1179
眼角桃花
眼角桃花 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 14:11

    You can also use numpy.argsort with advanced indexing:

    arr[np.arange(arr.shape[0])[:, None], (arr != 0).argsort(1, kind="mergesort")]
    
    #array([[ 2,  1, 23, 32],
    #       [ 0, 34,  3,  3],
    #       [ 0,  0,  3, 33],
    #       [ 0,  0,  0, 32]], dtype=int32)
    

提交回复
热议问题