Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.  2.]
 [ 0.  0.  0.  0.]
 [ 2.  0.  0.  1.]]

for example, If I wanted to right justify this array, it would look like:

[[ 5.  2.  0.  0.]
 [ 3.  2.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 2.  1.  0.  0.]]
like image 935
bnicholl Avatar asked May 26 '17 21:05

bnicholl


People also ask

How do you shift elements in a NumPy array?

If we want to right-shift or left-shift the elements of a NumPy array, we can use the numpy. roll() method in Python. The numpy. roll() method is used to roll array elements along a specified axis.

How do I order NumPy array in ascending order?

Use numpy. sort() function to sort the elements of NumPy array in an ordered sequence. The parameter arr is mandatory. If you execute this function on a one-dimensional array, it will return a one-dimensional sorted array containing elements in ascending order.

Is NumPy sort ascending or descending?

The sort() method from the NumPy module is used to sort NumPy arrays in Python. You can pass the array that you want to sort to the sort() method. The items in a numeric NumPy array are sorted in ascending order by default using the sort() method.


1 Answers

One vectorized approach making use of masks -

def justify_rows(a, side='left'):
    mask = a>0
    justified_mask = np.sort(mask,1)
    if side=='left':
        justified_mask = justified_mask[:,::-1]
    out = np.zeros_like(a) 
    out[justified_mask] = a[mask]
    return out

Basically the steps are :

  • Make a mask of greater than zeros.

  • Get a left or right justified mask where greater than elements are to be placed in a zeros initialized array. To get such a justified mask, we simply sort the mask from step-1 along each row, which throws the True ones in each row to the right. Thus, additionally we need flipping of each row for the left justified case.

  • Finally, use the justified mask to assign into output array and the mask from step-1 to select from input array.

Sample runs -

In [105]: a
Out[105]: 
array([[ 0.,  5.,  0.,  2.],
       [ 0.,  0.,  3.,  2.],
       [ 0.,  0.,  0.,  0.],
       [ 2.,  0.,  0.,  1.]])

In [106]: justify_rows(a, side='left')
Out[106]: 
array([[ 5.,  2.,  0.,  0.],
       [ 3.,  2.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 2.,  1.,  0.,  0.]])

In [107]: justify_rows(a, side='right')
Out[107]: 
array([[ 0.,  0.,  5.,  2.],
       [ 0.,  0.,  3.,  2.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  2.,  1.]])
like image 199
Divakar Avatar answered Sep 25 '22 10:09

Divakar