[Numpy-discussion] numpy masked array oddity

Robert Kern robert.kern@gmail....
Mon May 5 12:33:20 CDT 2008


On Mon, May 5, 2008 at 12:19 PM, Russell E. Owen <rowen@cesmail.net> wrote:
> The object returned by maskedArray.compressed() appears to be a normal
>  numpy array (based on repr output), but in reality it has some
>  surprising differences:
>
>  import numpy
>  a = numpy.arange(10, dtype=int)
>  b = numpy.zeros(10)
>  b[1] = 1
>  b[3] = 1
>  ma = numpy.core.ma.array(a, mask=b, dtype=float)
>  print ma
>  # [0.0 -- 2.0 -- 4.0 5.0 6.0 7.0 8.0 9.0]
>  c = ma.compressed()
>  print repr(c)
>  # array([ 0.  2.  4.  5.  6.  7.  8.  9.])
>  c.sort()
>  #Traceback (most recent call last):
>  #  File "<stdin>", line 1, in <module>
>  #  File
>  "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-pac
>  kages/#numpy/core/ma.py", line 2132, in not_implemented
>  #    raise NotImplementedError, "not yet implemented for numpy.ma arrays"
>  #NotImplementedError: not yet implemented for numpy.ma arrays
>  d = numpy.array(c)
>  d.sort()
>  # this works fine, as expected
>
>  Why is "c" in the example above not just a regular numpy array? It is
>  not a "live" view (based on a quick test), which seems sensible to me.
>  I've worked around the problem by making a copy (d in the example
>  above), but it seems most unfortunate to have to copy the data twice.

I don't know the reason why it's not an ndarray, but you don't have to
copy the data again to get one:

  c = ma.compressed().view(numpy.ndarray)

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
 -- Umberto Eco


More information about the Numpy-discussion mailing list