-3

I just realized that my masked array doesn't work as indices for selection.

When I do mathematical operations, such as max() it works, but not with selections.

import numpy as np

array = np.arange(3,8)
indices = np.ma.masked_array(np.arange(5),np.random.randint(0,2,5))

print('array data: %s' % array)
print('indices: %s' % indices)
print('-')
print('max index: %s - ok' % indices.max())
print('selecting on indices %s - not ok' % array[indices])

Am I missing something? Why wouldn't the above work?

Anonymous
  • 4,692
  • 8
  • 61
  • 91
  • What exactly are you trying to do? – ddejohn Feb 17 '22 at 23:31
  • I'm trying to select *non* masked indices: `array[indices]` – Anonymous Feb 17 '22 at 23:36
  • 1
    Please provide a concrete example. It's not clear why you aren't using normal masking syntax with negation. – ddejohn Feb 17 '22 at 23:38
  • Use the above pls. The issue is there is it always returns 5 elements. Basically ignoring the mask, even though `indices` is a masked array. – Anonymous Feb 17 '22 at 23:40
  • Do you mean `array[indices[~indices.mask]]`? I just thought of it. Seems like it's working. Is this the standard syntax? – Anonymous Feb 17 '22 at 23:43
  • What do you mean? `array[indices.mask]` is returning different numbers of elements every time I use it. *Please provide a concrete example* of your input and expected output. Please see this post on providing a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). Using randomly generated numbers is, almost by definition, not reproducible. – ddejohn Feb 17 '22 at 23:43

2 Answers2

1

EDIT Try to play around with n_elements. Mask and data size must be the same.

import numpy as np

n_elements = 5
x = 3

array = np.arange(x, x + n_elements)

indices = np.ma.masked_array(np.arange(n_elements), 
                             np.random.randint(0, 2, n_elements))

print('array data: %s' % array)
print('indices: %s' % indices)
print('-')
print('max index: %s - ok' % indices.max())
print('selecting on indices %s' % array[indices.mask])
print('excluding on indices %s' % array[~indices.mask])

ORIGINAL Maybe you're looking for the below?

array[indices.mask]
John Giorgio
  • 634
  • 3
  • 10
-2

Apparently, I should be using array[indices[~indices.mask]] instead of array[indices]. So instead of just specifying the indices array I should also explicitly apply it's mask on it.

Anonymous
  • 4,692
  • 8
  • 61
  • 91