[Numpy-discussion] take not respecting masked arrays?

Peter Shinners pete at shinners.org
Mon Mar 1 01:02:51 EST 2010

On 02/28/2010 08:01 PM, Pierre GM wrote:
> On Feb 28, 2010, at 8:59 PM, Peter Shinners wrote:
>> I have a 2D masked array that has indices into a 1D array. I want to use
>> some form of "take" to fetch the values into the 2D array. I've tried
>> both numpy.take and numpy.ma.take, but they both return a new unmasked
>> array.
> Mmh. Surprising.  np.ma.take should return a masked array if it's given a masked array as input. Can you pastebin the array that gives you trouble ? I need to investigate that.
> As a temporary workaround, use np.take on first the _data, then the _mask and construct a new masked array from the two results.

Here is the code as I would like it to work. 

import numpy as np

values = np.array((40, 18, 37, 9, 22))
index = np.arange(3)[None,:] + np.arange(5)[:,None]
mask = index >= len(values)

maskedindex = np.ma.array(index, mask=mask)

lookup = np.ma.take(values, maskedindex)
# This fails with an index error, but illegal indices are masked.
# It succeeds when mode="clip", but it does not return a masked array.
print lookup

More information about the NumPy-Discussion mailing list