Home > Back-end >  How to select on masked indices from non-masked array?
How to select on masked indices from non-masked array?

Time:02-18

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?

CodePudding user response:

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]

CodePudding user response:

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.

  • Related