Python: moving all elements greater than 0 to left and right in numpy array

前端 未结 3 623
囚心锁ツ
囚心锁ツ 2021-01-18 20:19

If I have an numpy array like the one below, how can I right justify or left justify the elements tat are greater than zero

[[ 0.  5.  0.  2.]
 [ 0.  0.  3.         


        
3条回答
  •  青春惊慌失措
    2021-01-18 21:02

    With the assumptions that every row contains at least one zero, and no negatives, this is just a partition:

    >>> np.partition(x, 1)
    array([[ 0.,  0.,  5.,  2.],
           [ 0.,  0.,  3.,  2.],
           [ 0.,  0.,  0.,  0.],
           [ 0.,  0.,  2.,  1.]])
    

    Edit: This shuffles the rows, so is little better than a sort

提交回复
热议问题