[Numpy-discussion] how to use masked arrays

Christopher Burns cburns@berkeley....
Wed May 14 01:18:06 CDT 2008


I'm finding it difficult to tell which methods/operations respect the
mask and which do not, in masked arrays.

mydata.filled returns a copy of the data (in a numpy array) with all
masked elements set to the fill_value.  So, masked respected, but data
returned as a new data-type when what I wanted was to set all masked
values in the array to the same value.

mydata.fill however modifies the data array in-place, modifies all
values regardless of the mask, and leaves the mask unchanged.

Assignment (mydata[:] = 10) sets all values in the slice and updates the mask.

Basic methods respect the mask, like mydata.mean(), but np.asarray
ignores the mask.

Example
------------
In [32]: mydata = ma.array([0,1,2,3,4,5], mask=[1,0,1,0,1,0])

In [34]: mydata
Out[34]:
masked_array(data = [-- 1 -- 3 -- 5],
      mask = [ True False  True False  True False],
      fill_value=999999)

In [35]: mydata.filled(np.nan)
Out[35]: array([0, 1, 0, 3, 0, 5])

In [36]: mydata.fill(np.nan)

In [37]: mydata
Out[37]:
masked_array(data = [-- 0 -- 0 -- 0],
      mask = [ True False  True False  True False],
      fill_value=999999)

In [38]: mydata.data
Out[38]: array([0, 0, 0, 0, 0, 0])

In [48]: mydata[:] = 456

In [49]: mydata
Out[49]:
masked_array(data = [456 456 456 456 456 456],
      mask = [False False False False False False],
      fill_value=999999)

In [53]: mydata = ma.array([0,1,2,3,4,5], mask=[1,0,1,0,1,0])

In [54]: mydata.mean()
Out[54]: 3.0

In [55]: np.asarray(mydata)
Out[55]: array([0, 1, 2, 3, 4, 5])


In summary, is there a tutorial that would show how to use masked
arrays?  Because at this point I'm confused and don't know how to use
them.

Google yields this out of data doc:
http://numpy.scipy.org/numpydoc/numpy-22.html

Thanks!

-- 
Christopher Burns
Computational Infrastructure for Research Labs
10 Giannini Hall, UC Berkeley
phone: 510.643.4014
http://cirl.berkeley.edu/


More information about the Numpy-discussion mailing list