0

Suppose that we have a 2D numpy array and we use np.ma.masked_where to mask some elements. In each row, we want to move all the masked elements to the end while preserving the order of rest of the elements. Is there an easy loop-free way to do that?

For example, suppose we have the following masked 2D matrix:

a = [1, --, 2
     4, 3, --
     --, --,5]

We want to return:

a = [1, 2, --
     4, 3, --
     5,--, --]
phuclv
  • 37,963
  • 15
  • 156
  • 475
Joe
  • 79
  • 3

1 Answers1

0

I didn't find any ma function could achieve this, but I think you could perform sort on mask array first

a = np.arange(9).reshape(3, 3)
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

np.ma.masked_where(a % 2 == 0, a)
masked_array(data =
 [[-- 1 --]
 [3 -- 5]
 [-- 7 --]],
             mask =
 [[ True False  True]
 [False  True False]
 [ True False  True]],
       fill_value = 999999)


a = a[np.arange(a.shape[0]).reshape(-1, 1), np.argsort(a % 2 == 0, axis=1, kind='mergesort')]
array([[1, 0, 2],
       [3, 5, 4],
       [7, 6, 8]])

np.ma.masked_where(a %2 == 0, a)
masked_array(data =
 [[1 -- --]
 [3 5 --]
 [7 -- --]],
             mask =
 [[False  True  True]
 [False False  True]
 [False  True  True]],
       fill_value = 999999)
Sacry
  • 535
  • 4
  • 9