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

前端 未结 3 631
囚心锁ツ
囚心锁ツ 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 20:58

    import numpy as np
    
    array = [ 
              [ 0.,  5.,  0.,  2.],
              [ 0.,  0.,  3.,  2.],
              [ 0.,  0.,  0.,  0.],
              [ 2.,  0.,  0.,  1.]
            ]
    
    
    def move(array, right = True):
      temp = []
      for x in array:
        x = np.array(x)
        #check positive arrays
        if len(np.where(x == 0)[0]) != len(x):
          if right:
            # little faster, compare to [::-1]
            # nonzero on right
            temp.append(x[np.argsort(-x)])
          else:
            # nonzero on left
            temp.append(np.sort(x))
        else:
            # no interchange needed
            temp.append(x)
      return temp
    
    print (move(array, 1))
    
    [array([ 5.,  2.,  0.,  0.]), array([ 3.,  2.,  0.,  0.]), array([ 0.,  0.,  0.,  0.]), array([ 2.,  1.,  0.,  0.])]
    
    print (move(array, 0))
    
    [array([ 0.,  0.,  2.,  5.]), array([ 0.,  0.,  2.,  3.]), array([ 0.,  0.,  0.,  0.]), array([ 0.,  0.,  1.,  2.])]
    
    print (np.concatenate(list(zip(move(array, 1))), axis=0))
    
    [[ 5.  2.  0.  0.]
     [ 3.  2.  0.  0.]
     [ 0.  0.  0.  0.]
     [ 2.  1.  0.  0.]]
    

提交回复
热议问题