module documentation

numpy.ma : a package to handle missing or invalid values.

This package was initially written for numarray by Paul F. Dubois at Lawrence Livermore National Laboratory. In 2006, the package was completely rewritten by Pierre Gerard-Marchant (University of Georgia) to make the MaskedArray class a subclass of ndarray, and to improve support of structured arrays.

Copyright 1999, 2000, 2001 Regents of the University of California. Released for unlimited redistribution.

  • Adapted for numpy_core 2005 by Travis Oliphant and (mainly) Paul Dubois.
  • Subclassing of the base ndarray 2006 by Pierre Gerard-Marchant (pgmdevlist_AT_gmail_DOT_com)
  • Improvements suggested by Reggie Dugard (reggie_AT_merfinllc_DOT_com)
Class MaskedArray An array class with possibly masked values.
Class MaskedConstant No class docstring; 0/1 class variable, 2/13 methods, 0/1 class method documented
Class MaskedIterator Flat iterator object to iterate over masked arrays.
Class mvoid Fake a 'void' object to use for masked array with structured dtypes.
Exception MAError Class for masked array related errors.
Exception MaskedArrayFutureWarning Undocumented
Exception MaskError Class for mask related errors.
Function allclose Returns True if two arrays are element-wise equal within a tolerance.
Function allequal Return True if all entries of a and b are equal, using fill_value as a truth value where either or both are masked.
Function append Append values to the end of an array.
Function argsort Function version of the eponymous method.
Function array Shortcut to MaskedArray.
Function asanyarray Convert the input to a masked array, conserving subclasses.
Function asarray Convert the input to a masked array of the given data-type.
Function choose Use an index array to construct a new array from a list of choices.
Function common_fill_value Return the common filling value of two masked arrays, if any.
Function compressed Return all the non-masked data as a 1-D array.
Function concatenate Concatenate a sequence of arrays along the given axis.
Function convolve Returns the discrete, linear convolution of two one-dimensional sequences.
Function correlate Cross-correlation of two 1-dimensional sequences.
Function default_fill_value Return the default fill value for the argument object.
Function diag Extract a diagonal or construct a diagonal array.
Function doc_note Adds a Notes section to an existing docstring.
Function filled Return input as an array with masked data replaced by a fill value.
Function fix_invalid Return input with invalid data masked and replaced by a fill value.
Function flatten_mask Returns a completely flattened version of the mask, where nested fields are collapsed.
Function flatten_structured_array Flatten a structured array.
Function fromfile Undocumented
Function fromflex Build a masked array from a suitable flexible-type array.
Function get_fill_value Return the filling value of a, if any. Otherwise, returns the default filling value for that type.
Function get_masked_subclass Return the youngest subclass of MaskedArray from a list of (masked) arrays.
Function get_object_signature Get the signature from obj
Function getdata Return the data of a masked array as an ndarray.
Function getmask Return the mask of a masked array, or nomask.
Function getmaskarray Return the mask of a masked array, or full boolean array of False.
Function inner Returns the inner product of a and b for arrays of floating point types.
Function is_mask Return True if m is a valid, standard mask.
Function is_masked Determine whether input has masked values.
Function is_string_or_list_of_strings Undocumented
Function isMaskedArray Test whether input is an instance of MaskedArray.
Function left_shift Shift the bits of an integer to the left.
Function make_mask Create a boolean mask from an array.
Function make_mask_descr Construct a dtype description list from a given dtype.
Function make_mask_none Return a boolean mask of the given shape, filled with False.
Function mask_or Combine two masks with the logical_or operator.
Function masked_equal Mask an array where equal to a given value.
Function masked_greater Mask an array where greater than a given value.
Function masked_greater_equal Mask an array where greater than or equal to a given value.
Function masked_inside Mask an array inside a given interval.
Function masked_invalid Mask an array where invalid values occur (NaNs or infs).
Function masked_less Mask an array where less than a given value.
Function masked_less_equal Mask an array where less than or equal to a given value.
Function masked_not_equal Mask an array where not equal to a given value.
Function masked_object Mask the array x where the data are exactly equal to value.
Function masked_outside Mask an array outside a given interval.
Function masked_values Mask using floating point equality.
Function masked_where Mask an array where a condition is met.
Function max Undocumented
Function maximum_fill_value Return the minimum value that can be represented by the dtype of an object.
Function min Undocumented
Function minimum_fill_value Return the maximum value that can be represented by the dtype of an object.
Function ndim maskedarray version of the numpy function.
Function outer maskedarray version of the numpy function.
Function power Returns element-wise base array raised to power from second array.
Function ptp Undocumented
Function put Set storage-indexed locations to corresponding values.
Function putmask Changes elements of an array based on conditional and input values.
Function reshape Returns an array containing the same data with a new shape.
Function resize Return a new masked array with the specified size and shape.
Function right_shift Shift the bits of an integer to the right.
Function round_ Return a copy of a, rounded to 'decimals' places.
Function set_fill_value Set the filling value of a, if a is a masked array.
Function shape maskedarray version of the numpy function.
Function size maskedarray version of the numpy function.
Function sort Return a sorted copy of the masked array.
Function take No summary
Function transpose Permute the dimensions of an array.
Function where Return a masked array with elements from x or y, depending on condition.
Variable abs Undocumented
Variable absolute Undocumented
Variable add Undocumented
Variable all Undocumented
Variable alltrue Undocumented
Variable angle Undocumented
Variable anom Undocumented
Variable anomalies Undocumented
Variable any Undocumented
Variable arange Undocumented
Variable arccos Undocumented
Variable arccosh Undocumented
Variable arcsin Undocumented
Variable arcsinh Undocumented
Variable arctan Undocumented
Variable arctan2 Undocumented
Variable arctanh Undocumented
Variable argmax Undocumented
Variable argmin Undocumented
Variable around Undocumented
Variable bitwise_and Undocumented
Variable bitwise_or Undocumented
Variable bitwise_xor Undocumented
Variable ceil Undocumented
Variable clip Undocumented
Variable compress Undocumented
Variable conjugate Undocumented
Variable copy Undocumented
Variable cos Undocumented
Variable cosh Undocumented
Variable count Undocumented
Variable cumprod Undocumented
Variable cumsum Undocumented
Variable default_filler Undocumented
Variable diagonal Undocumented
Variable diff Undocumented
Variable divide Undocumented
Variable empty Undocumented
Variable empty_like Undocumented
Variable equal Undocumented
Variable exp Undocumented
Variable fabs Undocumented
Variable float_types_list Undocumented
Variable floor Undocumented
Variable floor_divide Undocumented
Variable fmod Undocumented
Variable frombuffer Undocumented
Variable fromfunction Undocumented
Variable greater Undocumented
Variable greater_equal Undocumented
Variable harden_mask Undocumented
Variable hypot Undocumented
Variable identity Undocumented
Variable ids Undocumented
Variable indices Undocumented
Variable less Undocumented
Variable less_equal Undocumented
Variable log Undocumented
Variable log10 Undocumented
Variable log2 Undocumented
Variable logical_and Undocumented
Variable logical_not Undocumented
Variable logical_or Undocumented
Variable logical_xor Undocumented
Variable masked Undocumented
Variable masked_print_option Undocumented
Variable masked_singleton Undocumented
Variable maximum Undocumented
Variable mean Undocumented
Variable minimum Undocumented
Variable mod Undocumented
Variable multiply Undocumented
Variable negative Undocumented
Variable nomask Undocumented
Variable nonzero Undocumented
Variable not_equal Undocumented
Variable ones Undocumented
Variable ones_like Undocumented
Variable prod Undocumented
Variable product Undocumented
Variable ravel Undocumented
Variable remainder Undocumented
Variable repeat Undocumented
Variable shrink_mask Undocumented
Variable sin Undocumented
Variable sinh Undocumented
Variable soften_mask Undocumented
Variable sqrt Undocumented
Variable squeeze Undocumented
Variable std Undocumented
Variable subtract Undocumented
Variable sum Undocumented
Variable swapaxes Undocumented
Variable tan Undocumented
Variable tanh Undocumented
Variable trace Undocumented
Variable true_divide Undocumented
Variable ufunc_domain Undocumented
Variable ufunc_fills Undocumented
Variable var Undocumented
Variable zeros Undocumented
Variable zeros_like Undocumented
Class _convert2ma Convert functions from numpy to numpy.ma.
Class _DomainCheckInterval Define a valid interval, so that :
Class _DomainedBinaryOperation Define binary operations that have a domain, like divide.
Class _DomainGreater DomainGreater(v)(x) is True where x <= v.
Class _DomainGreaterEqual DomainGreaterEqual(v)(x) is True where x < v.
Class _DomainSafeDivide Define a domain for safe division.
Class _DomainTan Define a valid interval for the tan function, so that:
Class _extrema_operation Generic class for maximum/minimum functions.
Class _frommethod Define functions from existing MaskedArray methods.
Class _MaskedBinaryOperation Define masked version of binary operations, where invalid values are pre-masked.
Class _MaskedPrintOption Handle the string used to represent missing data in a masked array.
Class _MaskedUFunc Undocumented
Class _MaskedUnaryOperation Defines masked version of unary operations, where invalid values are pre-masked.
Function _arraymethod Return a class method wrapper around a basic array method.
Function _check_fill_value Private function validating the given fill_value for the given dtype.
Function _check_mask_axis Check whether there are masked values along the given axis
Function _convolve_or_correlate Helper function for ma.correlate and ma.convolve
Function _deprecate_argsort_axis Adjust the axis passed to argsort, warning if necessary
Function _extremum_fill_value Undocumented
Function _get_dtype_of Convert the argument for *_fill_value into a dtype
Function _mareconstruct Internal function that builds a new MaskedArray from the information stored in a pickle.
Function _recursive_fill_value Recursively produce a fill value for dtype, calling f on scalar dtypes
Function _recursive_filled Recursively fill a with fill_value.
Function _recursive_mask_or Undocumented
Function _recursive_printoption Puts printoptions in result where mask is True.
Function _recursive_set_fill_value Create a fill value for a structured dtype.
Function _replace_dtype_fields Construct a dtype description list from a given dtype.
Function _replace_dtype_fields_recursive Private function allowing recursion in _replace_dtype_fields.
Function _shrink_mask Shrink a mask to nomask if possible
Variable _legacy_print_templates Undocumented
def allclose(a, b, masked_equal=True, rtol=1e-05, atol=1e-08): (source)

Returns True if two arrays are element-wise equal within a tolerance.

This function is equivalent to allclose except that masked values are treated as equal (default) or unequal, depending on the masked_equal argument.

See Also

all, any

numpy.allclose
the non-masked allclose.

Notes

If the following equation is element-wise True, then allclose returns True:

absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))

Return True if all elements of a and b are equal subject to given tolerances.

Examples

>>> a = np.ma.array([1e10, 1e-7, 42.0], mask=[0, 0, 1])
>>> a
masked_array(data=[10000000000.0, 1e-07, --],
             mask=[False, False,  True],
       fill_value=1e+20)
>>> b = np.ma.array([1e10, 1e-8, -42.0], mask=[0, 0, 1])
>>> np.ma.allclose(a, b)
False
>>> a = np.ma.array([1e10, 1e-8, 42.0], mask=[0, 0, 1])
>>> b = np.ma.array([1.00001e10, 1e-9, -42.0], mask=[0, 0, 1])
>>> np.ma.allclose(a, b)
True
>>> np.ma.allclose(a, b, masked_equal=False)
False

Masked values are not compared directly.

>>> a = np.ma.array([1e10, 1e-8, 42.0], mask=[0, 0, 1])
>>> b = np.ma.array([1.00001e10, 1e-9, 42.0], mask=[0, 0, 1])
>>> np.ma.allclose(a, b)
True
>>> np.ma.allclose(a, b, masked_equal=False)
False
Parameters
a:array_likeInput arrays to compare.
b:array_likeInput arrays to compare.
masked_equal:bool, optionalWhether masked values in a and b are considered equal (True) or not (False). They are considered equal by default.
rtol:float, optionalRelative tolerance. The relative difference is equal to rtol * b. Default is 1e-5.
atol:float, optionalAbsolute tolerance. The absolute difference is equal to atol. Default is 1e-8.
Returns
booly - Returns True if the two arrays are equal within the given tolerance, False otherwise. If either array contains NaN, then False is returned.
def allequal(a, b, fill_value=True): (source)

Return True if all entries of a and b are equal, using fill_value as a truth value where either or both are masked.

Examples

>>> a = np.ma.array([1e10, 1e-7, 42.0], mask=[0, 0, 1])
>>> a
masked_array(data=[10000000000.0, 1e-07, --],
             mask=[False, False,  True],
       fill_value=1e+20)
>>> b = np.array([1e10, 1e-7, -42.0])
>>> b
array([  1.00000000e+10,   1.00000000e-07,  -4.20000000e+01])
>>> np.ma.allequal(a, b, fill_value=False)
False
>>> np.ma.allequal(a, b)
True
Parameters
a:array_likeInput arrays to compare.
b:array_likeInput arrays to compare.
fill_value:bool, optionalWhether masked values in a or b are considered equal (True) or not (False).
Returns
booly - Returns True if the two arrays are equal within the given tolerance, False otherwise. If either array contains NaN, then False is returned.
def append(a, b, axis=None): (source)

Append values to the end of an array.

New in version 1.9.0.

See Also

numpy.append
Equivalent function in the top-level NumPy module.

Examples

>>> import numpy.ma as ma
>>> a = ma.masked_values([1, 2, 3], 2)
>>> b = ma.masked_values([[4, 5, 6], [7, 8, 9]], 7)
>>> ma.append(a, b)
masked_array(data=[1, --, 3, 4, 5, 6, --, 8, 9],
             mask=[False,  True, False, False, False, False,  True, False,
                   False],
       fill_value=999999)
Parameters
a:array_likeValues are appended to a copy of this array.
b:array_likeThese values are appended to a copy of a. It must be of the correct shape (the same shape as a, excluding axis). If axis is not specified, b can be any shape and will be flattened before use.
axis:int, optionalThe axis along which v are appended. If axis is not given, both a and b are flattened before use.
Returns
MaskedArrayappend - A copy of a with b appended to axis. Note that append does not occur in-place: a new array is allocated and filled. If axis is None, the result is a flattened array.
def argsort(a, axis=np._NoValue, kind=None, order=None, endwith=True, fill_value=None): (source)

Function version of the eponymous method.

def array(data, dtype=None, copy=False, order=None, mask=nomask, fill_value=None, keep_mask=True, hard_mask=False, shrink=True, subok=True, ndmin=0): (source)

Shortcut to MaskedArray.

The options are in a different order for convenience and backwards compatibility.

def asanyarray(a, dtype=None): (source)

Convert the input to a masked array, conserving subclasses.

If a is a subclass of MaskedArray, its class is conserved. No copy is performed if the input is already an ndarray.

See Also

asarray
Similar to asanyarray, but does not conserve subclass.

Examples

>>> x = np.arange(10.).reshape(2, 5)
>>> x
array([[0., 1., 2., 3., 4.],
       [5., 6., 7., 8., 9.]])
>>> np.ma.asanyarray(x)
masked_array(
  data=[[0., 1., 2., 3., 4.],
        [5., 6., 7., 8., 9.]],
  mask=False,
  fill_value=1e+20)
>>> type(np.ma.asanyarray(x))
<class 'numpy.ma.core.MaskedArray'>
Parameters
a:array_likeInput data, in any form that can be converted to an array.
dtype:dtype, optionalBy default, the data-type is inferred from the input data.
order:{'C', 'F'}, optionalWhether to use row-major ('C') or column-major ('FORTRAN') memory representation. Default is 'C'.
Returns
MaskedArrayout - MaskedArray interpretation of a.
def asarray(a, dtype=None, order=None): (source)

Convert the input to a masked array of the given data-type.

No copy is performed if the input is already an ndarray. If a is a subclass of MaskedArray, a base class MaskedArray is returned.

See Also

asanyarray
Similar to asarray, but conserves subclasses.

Examples

>>> x = np.arange(10.).reshape(2, 5)
>>> x
array([[0., 1., 2., 3., 4.],
       [5., 6., 7., 8., 9.]])
>>> np.ma.asarray(x)
masked_array(
  data=[[0., 1., 2., 3., 4.],
        [5., 6., 7., 8., 9.]],
  mask=False,
  fill_value=1e+20)
>>> type(np.ma.asarray(x))
<class 'numpy.ma.core.MaskedArray'>
Parameters
a:array_likeInput data, in any form that can be converted to a masked array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists, ndarrays and masked arrays.
dtype:dtype, optionalBy default, the data-type is inferred from the input data.
order:{'C', 'F'}, optionalWhether to use row-major ('C') or column-major ('FORTRAN') memory representation. Default is 'C'.
Returns
MaskedArrayout - Masked array interpretation of a.
def choose(indices, choices, out=None, mode='raise'): (source)

Use an index array to construct a new array from a list of choices.

Given an array of integers and a list of n choice arrays, this method will create a new array that merges each of the choice arrays. Where a value in index is i, the new array will have the value that choices[i] contains in the same place.

See Also

choose
equivalent function

Examples

>>> choice = np.array([[1,1,1], [2,2,2], [3,3,3]])
>>> a = np.array([2, 1, 0])
>>> np.ma.choose(a, choice)
masked_array(data=[3, 2, 1],
             mask=False,
       fill_value=999999)
Parameters
indices:ndarray of intsThis array must contain integers in [0, n-1], where n is the number of choices.
choices:sequence of arraysChoice arrays. The index array and all of the choices should be broadcastable to the same shape.
out:array, optionalIf provided, the result will be inserted into this array. It should be of the appropriate shape and dtype.
mode:{'raise', 'wrap', 'clip'}, optional

Specifies how out-of-bounds indices will behave.

  • 'raise' : raise an error
  • 'wrap' : wrap around
  • 'clip' : clip to the range
Returns
arraymerged_array
def common_fill_value(a, b): (source)

Return the common filling value of two masked arrays, if any.

If a.fill_value == b.fill_value, return the fill value, otherwise return None.

Examples

>>> x = np.ma.array([0, 1.], fill_value=3)
>>> y = np.ma.array([0, 1.], fill_value=3)
>>> np.ma.common_fill_value(x, y)
3.0
Parameters
a:MaskedArrayThe masked arrays for which to compare fill values.
b:MaskedArrayThe masked arrays for which to compare fill values.
Returns
scalar or Nonefill_value - The common fill value, or None.
def compressed(x): (source)

Return all the non-masked data as a 1-D array.

This function is equivalent to calling the "compressed" method of a ma.MaskedArray, see ma.MaskedArray.compressed for details.

See Also

ma.MaskedArray.compressed
Equivalent method.
def concatenate(arrays, axis=0): (source)

Concatenate a sequence of arrays along the given axis.

See Also

numpy.concatenate
Equivalent function in the top-level NumPy module.

Examples

>>> import numpy.ma as ma
>>> a = ma.arange(3)
>>> a[1] = ma.masked
>>> b = ma.arange(2, 5)
>>> a
masked_array(data=[0, --, 2],
             mask=[False,  True, False],
       fill_value=999999)
>>> b
masked_array(data=[2, 3, 4],
             mask=False,
       fill_value=999999)
>>> ma.concatenate([a, b])
masked_array(data=[0, --, 2, 2, 3, 4],
             mask=[False,  True, False, False, False, False],
       fill_value=999999)
Parameters
arrays:sequence of array_likeThe arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).
axis:int, optionalThe axis along which the arrays will be joined. Default is 0.
Returns
MaskedArrayresult - The concatenated array with any masked entries preserved.
def convolve(a, v, mode='full', propagate_mask=True): (source)

Returns the discrete, linear convolution of two one-dimensional sequences.

See Also

numpy.convolve
Equivalent function in the top-level NumPy module.
Parameters
a:array_likeInput sequences.
v:array_likeInput sequences.
mode:{'valid', 'same', 'full'}, optionalRefer to the np.convolve docstring.
propagate_mask:boolIf True, then if any masked element is included in the sum for a result element, then the result is masked. If False, then the result element is only masked if no non-masked cells contribute towards it
Returns
MaskedArrayout - Discrete, linear convolution of a and v.
def correlate(a, v, mode='valid', propagate_mask=True): (source)

Cross-correlation of two 1-dimensional sequences.

See Also

numpy.correlate
Equivalent function in the top-level NumPy module.
Parameters
a:array_likeInput sequences.
v:array_likeInput sequences.
mode:{'valid', 'same', 'full'}, optionalRefer to the np.convolve docstring. Note that the default is 'valid', unlike convolve, which uses 'full'.
propagate_mask:boolIf True, then a result element is masked if any masked element contributes towards it. If False, then a result element is only masked if no non-masked element contribute towards it
Returns
MaskedArrayout - Discrete cross-correlation of a and v.
def default_fill_value(obj): (source)

Return the default fill value for the argument object.

The default filling value depends on the datatype of the input array or the type of the input scalar:

datatype default
bool True
int 999999
float 1.e20
complex 1.e20+0j
object '?'
string 'N/A'

For structured types, a structured scalar is returned, with each field the default fill value for its type.

For subarray types, the fill value is an array of the same size containing the default scalar fill value.

Examples

>>> np.ma.default_fill_value(1)
999999
>>> np.ma.default_fill_value(np.array([1.1, 2., np.pi]))
1e+20
>>> np.ma.default_fill_value(np.dtype(complex))
(1e+20+0j)
Parameters
obj:ndarray, dtype or scalarThe array data-type or scalar for which the default fill value is returned.
Returns
scalarfill_value - The default fill value.
def diag(v, k=0): (source)

Extract a diagonal or construct a diagonal array.

This function is the equivalent of numpy.diag that takes masked values into account, see numpy.diag for details.

See Also

numpy.diag
Equivalent function for ndarrays.
def doc_note(initialdoc, note): (source)

Adds a Notes section to an existing docstring.

def filled(a, fill_value=None): (source)

Return input as an array with masked data replaced by a fill value.

If a is not a MaskedArray, a itself is returned. If a is a MaskedArray and fill_value is None, fill_value is set to a.fill_value.

See Also

compressed

Examples

>>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0],
...                                                   [1, 0, 0],
...                                                   [0, 0, 0]])
>>> x.filled()
array([[999999,      1,      2],
       [999999,      4,      5],
       [     6,      7,      8]])
>>> x.filled(fill_value=333)
array([[333,   1,   2],
       [333,   4,   5],
       [  6,   7,   8]])
>>> x.filled(fill_value=np.arange(3))
array([[0, 1, 2],
       [0, 4, 5],
       [6, 7, 8]])
Parameters
a:MaskedArray or array_likeAn input object.
fill_value:array_like, optional.Can be scalar or non-scalar. If non-scalar, the resulting filled array should be broadcastable over input array. Default is None.
Returns
ndarraya - The filled array.
def fix_invalid(a, mask=nomask, copy=True, fill_value=None): (source)

Return input with invalid data masked and replaced by a fill value.

Invalid data means values of nan, inf, etc.

Notes

A copy is performed by default.

Examples

>>> x = np.ma.array([1., -1, np.nan, np.inf], mask=[1] + [0]*3)
>>> x
masked_array(data=[--, -1.0, nan, inf],
             mask=[ True, False, False, False],
       fill_value=1e+20)
>>> np.ma.fix_invalid(x)
masked_array(data=[--, -1.0, --, --],
             mask=[ True, False,  True,  True],
       fill_value=1e+20)
>>> fixed = np.ma.fix_invalid(x)
>>> fixed.data
array([ 1.e+00, -1.e+00,  1.e+20,  1.e+20])
>>> x.data
array([ 1., -1., nan, inf])
Parameters
a:array_likeInput array, a (subclass of) ndarray.
mask:sequence, optionalMask. Must be convertible to an array of booleans with the same shape as data. True indicates a masked (i.e. invalid) data.
copy:bool, optionalWhether to use a copy of a (True) or to fix a in place (False). Default is True.
fill_value:scalar, optionalValue used for fixing invalid data. Default is None, in which case the a.fill_value is used.
Returns
MaskedArrayb - The input array with invalid entries fixed.
def flatten_mask(mask): (source)

Returns a completely flattened version of the mask, where nested fields are collapsed.

Examples

>>> mask = np.array([0, 0, 1])
>>> np.ma.flatten_mask(mask)
array([False, False,  True])
>>> mask = np.array([(0, 0), (0, 1)], dtype=[('a', bool), ('b', bool)])
>>> np.ma.flatten_mask(mask)
array([False, False, False,  True])
>>> mdtype = [('a', bool), ('b', [('ba', bool), ('bb', bool)])]
>>> mask = np.array([(0, (0, 0)), (0, (0, 1))], dtype=mdtype)
>>> np.ma.flatten_mask(mask)
array([False, False, False, False, False,  True])
Parameters
mask:array_likeInput array, which will be interpreted as booleans.
Returns
ndarray of boolsflattened_mask - The flattened input.
def flatten_structured_array(a): (source)

Flatten a structured array.

The data type of the output is chosen such that it can represent all of the (nested) fields.

Examples

>>> ndtype = [('a', int), ('b', float)]
>>> a = np.array([(1, 1), (2, 2)], dtype=ndtype)
>>> np.ma.flatten_structured_array(a)
array([[1., 1.],
       [2., 2.]])
Parameters
a:structured array
Returns
masked array or ndarrayoutput - A flattened masked array if the input is a masked array, otherwise a standard ndarray.
def fromfile(file, dtype=float, count=-1, sep=''): (source)

Undocumented

def fromflex(fxarray): (source)

Build a masked array from a suitable flexible-type array.

The input array has to have a data-type with _data and _mask fields. This type of array is output by MaskedArray.toflex.

See Also

MaskedArray.toflex
Build a flexible-type array from a masked array.

Examples

>>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[0] + [1, 0] * 4)
>>> rec = x.toflex()
>>> rec
array([[(0, False), (1,  True), (2, False)],
       [(3,  True), (4, False), (5,  True)],
       [(6, False), (7,  True), (8, False)]],
      dtype=[('_data', '<i8'), ('_mask', '?')])
>>> x2 = np.ma.fromflex(rec)
>>> x2
masked_array(
  data=[[0, --, 2],
        [--, 4, --],
        [6, --, 8]],
  mask=[[False,  True, False],
        [ True, False,  True],
        [False,  True, False]],
  fill_value=999999)

Extra fields can be present in the structured array but are discarded:

>>> dt = [('_data', '<i4'), ('_mask', '|b1'), ('field3', '<f4')]
>>> rec2 = np.zeros((2, 2), dtype=dt)
>>> rec2
array([[(0, False, 0.), (0, False, 0.)],
       [(0, False, 0.), (0, False, 0.)]],
      dtype=[('_data', '<i4'), ('_mask', '?'), ('field3', '<f4')])
>>> y = np.ma.fromflex(rec2)
>>> y
masked_array(
  data=[[0, 0],
        [0, 0]],
  mask=[[False, False],
        [False, False]],
  fill_value=999999,
  dtype=int32)
Parameters
fxarray:ndarrayThe structured input array, containing _data and _mask fields. If present, other fields are discarded.
Returns
MaskedArrayresult - The constructed masked array.
def get_fill_value(a): (source)

Return the filling value of a, if any. Otherwise, returns the default filling value for that type.

def get_masked_subclass(*arrays): (source)

Return the youngest subclass of MaskedArray from a list of (masked) arrays.

In case of siblings, the first listed takes over.

def get_object_signature(obj): (source)

Get the signature from obj

def getdata(a, subok=True): (source)

Return the data of a masked array as an ndarray.

Return the data of a (if any) as an ndarray if a is a MaskedArray, else return a as a ndarray or subclass (depending on subok) if not.

See Also

getmask
Return the mask of a masked array, or nomask.
getmaskarray
Return the mask of a masked array, or full array of False.

Examples

>>> import numpy.ma as ma
>>> a = ma.masked_equal([[1,2],[3,4]], 2)
>>> a
masked_array(
  data=[[1, --],
        [3, 4]],
  mask=[[False,  True],
        [False, False]],
  fill_value=2)
>>> ma.getdata(a)
array([[1, 2],
       [3, 4]])

Equivalently use the MaskedArray data attribute.

>>> a.data
array([[1, 2],
       [3, 4]])
Parameters
a:array_likeInput MaskedArray, alternatively a ndarray or a subclass thereof.
subok:boolWhether to force the output to be a pure ndarray (False) or to return a subclass of ndarray if appropriate (True, default).
def getmask(a): (source)

Return the mask of a masked array, or nomask.

Return the mask of a as an ndarray if a is a MaskedArray and the mask is not nomask, else return nomask. To guarantee a full array of booleans of the same shape as a, use getmaskarray.

See Also

getdata
Return the data of a masked array as an ndarray.
getmaskarray
Return the mask of a masked array, or full array of False.

Examples

>>> import numpy.ma as ma
>>> a = ma.masked_equal([[1,2],[3,4]], 2)
>>> a
masked_array(
  data=[[1, --],
        [3, 4]],
  mask=[[False,  True],
        [False, False]],
  fill_value=2)
>>> ma.getmask(a)
array([[False,  True],
       [False, False]])

Equivalently use the MaskedArray mask attribute.

>>> a.mask
array([[False,  True],
       [False, False]])

Result when mask == nomask

>>> b = ma.masked_array([[1,2],[3,4]])
>>> b
masked_array(
  data=[[1, 2],
        [3, 4]],
  mask=False,
  fill_value=999999)
>>> ma.nomask
False
>>> ma.getmask(b) == ma.nomask
True
>>> b.mask == ma.nomask
True
Parameters
a:array_likeInput MaskedArray for which the mask is required.
def getmaskarray(arr): (source)

Return the mask of a masked array, or full boolean array of False.

Return the mask of arr as an ndarray if arr is a MaskedArray and the mask is not nomask, else return a full boolean array of False of the same shape as arr.

See Also

getmask
Return the mask of a masked array, or nomask.
getdata
Return the data of a masked array as an ndarray.

Examples

>>> import numpy.ma as ma
>>> a = ma.masked_equal([[1,2],[3,4]], 2)
>>> a
masked_array(
  data=[[1, --],
        [3, 4]],
  mask=[[False,  True],
        [False, False]],
  fill_value=2)
>>> ma.getmaskarray(a)
array([[False,  True],
       [False, False]])

Result when mask == nomask

>>> b = ma.masked_array([[1,2],[3,4]])
>>> b
masked_array(
  data=[[1, 2],
        [3, 4]],
  mask=False,
  fill_value=999999)
>>> ma.getmaskarray(b)
array([[False, False],
       [False, False]])
Parameters
arr:array_likeInput MaskedArray for which the mask is required.
def inner(a, b): (source)

Returns the inner product of a and b for arrays of floating point types.

Like the generic NumPy equivalent the product sum is over the last dimension of a and b. The first argument is not conjugated.

def is_mask(m): (source)

Return True if m is a valid, standard mask.

This function does not check the contents of the input, only that the type is MaskType. In particular, this function returns False if the mask has a flexible dtype.

See Also

ma.isMaskedArray
Test whether input is an instance of MaskedArray.

Examples

>>> import numpy.ma as ma
>>> m = ma.masked_equal([0, 1, 0, 2, 3], 0)
>>> m
masked_array(data=[--, 1, --, 2, 3],
             mask=[ True, False,  True, False, False],
       fill_value=0)
>>> ma.is_mask(m)
False
>>> ma.is_mask(m.mask)
True

Input must be an ndarray (or have similar attributes) for it to be considered a valid mask.

>>> m = [False, True, False]
>>> ma.is_mask(m)
False
>>> m = np.array([False, True, False])
>>> m
array([False,  True, False])
>>> ma.is_mask(m)
True

Arrays with complex dtypes don't return True.

>>> dtype = np.dtype({'names':['monty', 'pithon'],
...                   'formats':[bool, bool]})
>>> dtype
dtype([('monty', '|b1'), ('pithon', '|b1')])
>>> m = np.array([(True, False), (False, True), (True, False)],
...              dtype=dtype)
>>> m
array([( True, False), (False,  True), ( True, False)],
      dtype=[('monty', '?'), ('pithon', '?')])
>>> ma.is_mask(m)
False
Parameters
m:array_likeArray to test.
Returns
boolresult - True if m.dtype.type is MaskType, False otherwise.
def is_masked(x): (source)

Determine whether input has masked values.

Accepts any object as input, but always returns False unless the input is a MaskedArray containing masked values.

Examples

>>> import numpy.ma as ma
>>> x = ma.masked_equal([0, 1, 0, 2, 3], 0)
>>> x
masked_array(data=[--, 1, --, 2, 3],
             mask=[ True, False,  True, False, False],
       fill_value=0)
>>> ma.is_masked(x)
True
>>> x = ma.masked_equal([0, 1, 0, 2, 3], 42)
>>> x
masked_array(data=[0, 1, 0, 2, 3],
             mask=False,
       fill_value=42)
>>> ma.is_masked(x)
False

Always returns False if x isn't a MaskedArray.

>>> x = [False, True, False]
>>> ma.is_masked(x)
False
>>> x = 'a string'
>>> ma.is_masked(x)
False
Parameters
x:array_likeArray to check for masked values.
Returns
boolresult - True if x is a MaskedArray with masked values, False otherwise.
def is_string_or_list_of_strings(val): (source)

Undocumented

def isMaskedArray(x): (source)

Test whether input is an instance of MaskedArray.

This function returns True if x is an instance of MaskedArray and returns False otherwise. Any object is accepted as input.

See Also

isMA
Alias to isMaskedArray.
isarray
Alias to isMaskedArray.

Examples

>>> import numpy.ma as ma
>>> a = np.eye(3, 3)
>>> a
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])
>>> m = ma.masked_values(a, 0)
>>> m
masked_array(
  data=[[1.0, --, --],
        [--, 1.0, --],
        [--, --, 1.0]],
  mask=[[False,  True,  True],
        [ True, False,  True],
        [ True,  True, False]],
  fill_value=0.0)
>>> ma.isMaskedArray(a)
False
>>> ma.isMaskedArray(m)
True
>>> ma.isMaskedArray([0, 1, 2])
False
Parameters
x:objectObject to test.
Returns
boolresult - True if x is a MaskedArray.
def left_shift(a, n): (source)

Shift the bits of an integer to the left.

This is the masked array version of numpy.left_shift, for details see that function.

See Also

numpy.left_shift

def make_mask(m, copy=False, shrink=True, dtype=MaskType): (source)

Create a boolean mask from an array.

Return m as a boolean mask, creating a copy if necessary or requested. The function can accept any sequence that is convertible to integers, or nomask. Does not require that contents must be 0s and 1s, values of 0 are interpreted as False, everything else as True.

Examples

>>> import numpy.ma as ma
>>> m = [True, False, True, True]
>>> ma.make_mask(m)
array([ True, False,  True,  True])
>>> m = [1, 0, 1, 1]
>>> ma.make_mask(m)
array([ True, False,  True,  True])
>>> m = [1, 0, 2, -3]
>>> ma.make_mask(m)
array([ True, False,  True,  True])

Effect of the shrink parameter.

>>> m = np.zeros(4)
>>> m
array([0., 0., 0., 0.])
>>> ma.make_mask(m)
False
>>> ma.make_mask(m, shrink=False)
array([False, False, False, False])

Using a flexible dtype.

>>> m = [1, 0, 1, 1]
>>> n = [0, 1, 0, 0]
>>> arr = []
>>> for man, mouse in zip(m, n):
...     arr.append((man, mouse))
>>> arr
[(1, 0), (0, 1), (1, 0), (1, 0)]
>>> dtype = np.dtype({'names':['man', 'mouse'],
...                   'formats':[np.int64, np.int64]})
>>> arr = np.array(arr, dtype=dtype)
>>> arr
array([(1, 0), (0, 1), (1, 0), (1, 0)],
      dtype=[('man', '<i8'), ('mouse', '<i8')])
>>> ma.make_mask(arr, dtype=dtype)
array([(True, False), (False, True), (True, False), (True, False)],
      dtype=[('man', '|b1'), ('mouse', '|b1')])
Parameters
m:array_likePotential mask.
copy:bool, optionalWhether to return a copy of m (True) or m itself (False).
shrink:bool, optionalWhether to shrink m to nomask if all its values are False.
dtype:dtype, optionalData-type of the output mask. By default, the output mask has a dtype of MaskType (bool). If the dtype is flexible, each field has a boolean dtype. This is ignored when m is nomask, in which case nomask is always returned.
Returns
ndarrayresult - A boolean mask derived from m.
def make_mask_descr(ndtype): (source)

Construct a dtype description list from a given dtype.

Returns a new dtype object, with the type of all fields in ndtype to a boolean type. Field names are not altered.

Examples

>>> import numpy.ma as ma
>>> dtype = np.dtype({'names':['foo', 'bar'],
...                   'formats':[np.float32, np.int64]})
>>> dtype
dtype([('foo', '<f4'), ('bar', '<i8')])
>>> ma.make_mask_descr(dtype)
dtype([('foo', '|b1'), ('bar', '|b1')])
>>> ma.make_mask_descr(np.float32)
dtype('bool')
Parameters
ndtype:dtypeThe dtype to convert.
Returns
dtyperesult - A dtype that looks like ndtype, the type of all fields is boolean.
def make_mask_none(newshape, dtype=None): (source)

Return a boolean mask of the given shape, filled with False.

This function returns a boolean ndarray with all entries False, that can be used in common mask manipulations. If a complex dtype is specified, the type of each field is converted to a boolean type.

See Also

make_mask
Create a boolean mask from an array.
make_mask_descr
Construct a dtype description list from a given dtype.

Examples

>>> import numpy.ma as ma
>>> ma.make_mask_none((3,))
array([False, False, False])

Defining a more complex dtype.

>>> dtype = np.dtype({'names':['foo', 'bar'],
...                   'formats':[np.float32, np.int64]})
>>> dtype
dtype([('foo', '<f4'), ('bar', '<i8')])
>>> ma.make_mask_none((3,), dtype=dtype)
array([(False, False), (False, False), (False, False)],
      dtype=[('foo', '|b1'), ('bar', '|b1')])
Parameters
newshape:tupleA tuple indicating the shape of the mask.
dtype:{None, dtype}, optionalIf None, use a MaskType instance. Otherwise, use a new datatype with the same fields as dtype, converted to boolean types.
Returns
ndarrayresult - An ndarray of appropriate shape and dtype, filled with False.
def mask_or(m1, m2, copy=False, shrink=True): (source)

Combine two masks with the logical_or operator.

The result may be a view on m1 or m2 if the other is nomask (i.e. False).

Examples

>>> m1 = np.ma.make_mask([0, 1, 1, 0])
>>> m2 = np.ma.make_mask([1, 0, 0, 0])
>>> np.ma.mask_or(m1, m2)
array([ True,  True,  True, False])
Parameters
m1:array_likeInput masks.
m2:array_likeInput masks.
copy:bool, optionalIf copy is False and one of the inputs is nomask, return a view of the other input mask. Defaults to False.
shrink:bool, optionalWhether to shrink the output to nomask if all its values are False. Defaults to True.
Returns
output maskmask - The result masks values that are masked in either m1 or m2.
Raises
ValueErrorIf m1 and m2 have different flexible dtypes.
def masked_equal(x, value, copy=True): (source)

Mask an array where equal to a given value.

Return a MaskedArray, masked where the data in array x are equal to value. The fill_value of the returned MaskedArray is set to value.

For floating point arrays, consider using masked_values(x, value).

See Also

masked_where
Mask where a condition is met.
masked_values
Mask using floating point equality.

Examples

>>> import numpy.ma as ma
>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> ma.masked_equal(a, 2)
masked_array(data=[0, 1, --, 3],
             mask=[False, False,  True, False],
       fill_value=2)
def masked_greater(x, value, copy=True): (source)

Mask an array where greater than a given value.

This function is a shortcut to masked_where, with condition = (x > value).

See Also

masked_where
Mask where a condition is met.

Examples

>>> import numpy.ma as ma
>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> ma.masked_greater(a, 2)
masked_array(data=[0, 1, 2, --],
             mask=[False, False, False,  True],
       fill_value=999999)
def masked_greater_equal(x, value, copy=True): (source)

Mask an array where greater than or equal to a given value.

This function is a shortcut to masked_where, with condition = (x >= value).

See Also

masked_where
Mask where a condition is met.

Examples

>>> import numpy.ma as ma
>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> ma.masked_greater_equal(a, 2)
masked_array(data=[0, 1, --, --],
             mask=[False, False,  True,  True],
       fill_value=999999)
def masked_inside(x, v1, v2, copy=True): (source)

Mask an array inside a given interval.

Shortcut to masked_where, where condition is True for x inside the interval [v1,v2] (v1 <= x <= v2). The boundaries v1 and v2 can be given in either order.

See Also

masked_where
Mask where a condition is met.

Notes

The array x is prefilled with its filling value.

Examples

>>> import numpy.ma as ma
>>> x = [0.31, 1.2, 0.01, 0.2, -0.4, -1.1]
>>> ma.masked_inside(x, -0.3, 0.3)
masked_array(data=[0.31, 1.2, --, --, -0.4, -1.1],
             mask=[False, False,  True,  True, False, False],
       fill_value=1e+20)

The order of v1 and v2 doesn't matter.

>>> ma.masked_inside(x, 0.3, -0.3)
masked_array(data=[0.31, 1.2, --, --, -0.4, -1.1],
             mask=[False, False,  True,  True, False, False],
       fill_value=1e+20)
def masked_invalid(a, copy=True): (source)

Mask an array where invalid values occur (NaNs or infs).

This function is a shortcut to masked_where, with condition = ~(np.isfinite(a)). Any pre-existing mask is conserved. Only applies to arrays with a dtype where NaNs or infs make sense (i.e. floating point types), but accepts any array_like object.

See Also

masked_where
Mask where a condition is met.

Examples

>>> import numpy.ma as ma
>>> a = np.arange(5, dtype=float)
>>> a[2] = np.NaN
>>> a[3] = np.PINF
>>> a
array([ 0.,  1., nan, inf,  4.])
>>> ma.masked_invalid(a)
masked_array(data=[0.0, 1.0, --, --, 4.0],
             mask=[False, False,  True,  True, False],
       fill_value=1e+20)
def masked_less(x, value, copy=True): (source)

Mask an array where less than a given value.

This function is a shortcut to masked_where, with condition = (x < value).

See Also

masked_where
Mask where a condition is met.

Examples

>>> import numpy.ma as ma
>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> ma.masked_less(a, 2)
masked_array(data=[--, --, 2, 3],
             mask=[ True,  True, False, False],
       fill_value=999999)
def masked_less_equal(x, value, copy=True): (source)

Mask an array where less than or equal to a given value.

This function is a shortcut to masked_where, with condition = (x <= value).

See Also

masked_where
Mask where a condition is met.

Examples

>>> import numpy.ma as ma
>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> ma.masked_less_equal(a, 2)
masked_array(data=[--, --, --, 3],
             mask=[ True,  True,  True, False],
       fill_value=999999)
def masked_not_equal(x, value, copy=True): (source)

Mask an array where not equal to a given value.

This function is a shortcut to masked_where, with condition = (x != value).

See Also

masked_where
Mask where a condition is met.

Examples

>>> import numpy.ma as ma
>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> ma.masked_not_equal(a, 2)
masked_array(data=[--, --, 2, --],
             mask=[ True,  True, False,  True],
       fill_value=999999)
def masked_object(x, value, copy=True, shrink=True): (source)

Mask the array x where the data are exactly equal to value.

This function is similar to masked_values, but only suitable for object arrays: for floating point, use masked_values instead.

See Also

masked_where
Mask where a condition is met.
masked_equal
Mask where equal to a given value (integers).
masked_values
Mask using floating point equality.

Examples

>>> import numpy.ma as ma
>>> food = np.array(['green_eggs', 'ham'], dtype=object)
>>> # don't eat spoiled food
>>> eat = ma.masked_object(food, 'green_eggs')
>>> eat
masked_array(data=[--, 'ham'],
             mask=[ True, False],
       fill_value='green_eggs',
            dtype=object)
>>> # plain ol` ham is boring
>>> fresh_food = np.array(['cheese', 'ham', 'pineapple'], dtype=object)
>>> eat = ma.masked_object(fresh_food, 'green_eggs')
>>> eat
masked_array(data=['cheese', 'ham', 'pineapple'],
             mask=False,
       fill_value='green_eggs',
            dtype=object)

Note that mask is set to nomask if possible.

>>> eat
masked_array(data=['cheese', 'ham', 'pineapple'],
             mask=False,
       fill_value='green_eggs',
            dtype=object)
Parameters
x:array_likeArray to mask
value:objectComparison value
copy:{True, False}, optionalWhether to return a copy of x.
shrink:{True, False}, optionalWhether to collapse a mask full of False to nomask
Returns
MaskedArrayresult - The result of masking x where equal to value.
def masked_outside(x, v1, v2, copy=True): (source)

Mask an array outside a given interval.

Shortcut to masked_where, where condition is True for x outside the interval [v1,v2] (x < v1)|(x > v2). The boundaries v1 and v2 can be given in either order.

See Also

masked_where
Mask where a condition is met.

Notes

The array x is prefilled with its filling value.

Examples

>>> import numpy.ma as ma
>>> x = [0.31, 1.2, 0.01, 0.2, -0.4, -1.1]
>>> ma.masked_outside(x, -0.3, 0.3)
masked_array(data=[--, --, 0.01, 0.2, --, --],
             mask=[ True,  True, False, False,  True,  True],
       fill_value=1e+20)

The order of v1 and v2 doesn't matter.

>>> ma.masked_outside(x, 0.3, -0.3)
masked_array(data=[--, --, 0.01, 0.2, --, --],
             mask=[ True,  True, False, False,  True,  True],
       fill_value=1e+20)
def masked_values(x, value, rtol=1e-05, atol=1e-08, copy=True, shrink=True): (source)

Mask using floating point equality.

Return a MaskedArray, masked where the data in array x are approximately equal to value, determined using isclose. The default tolerances for masked_values are the same as those for isclose.

For integer types, exact equality is used, in the same way as masked_equal.

The fill_value is set to value and the mask is set to nomask if possible.

See Also

masked_where
Mask where a condition is met.
masked_equal
Mask where equal to a given value (integers).

Examples

>>> import numpy.ma as ma
>>> x = np.array([1, 1.1, 2, 1.1, 3])
>>> ma.masked_values(x, 1.1)
masked_array(data=[1.0, --, 2.0, --, 3.0],
             mask=[False,  True, False,  True, False],
       fill_value=1.1)

Note that mask is set to nomask if possible.

>>> ma.masked_values(x, 2.1)
masked_array(data=[1. , 1.1, 2. , 1.1, 3. ],
             mask=False,
       fill_value=2.1)

Unlike masked_equal, masked_values can perform approximate equalities.

>>> ma.masked_values(x, 2.1, atol=1e-1)
masked_array(data=[1.0, 1.1, --, 1.1, 3.0],
             mask=[False, False,  True, False, False],
       fill_value=2.1)
Parameters
x:array_likeArray to mask.
value:floatMasking value.
rtol:float, optionalTolerance parameters passed on to isclose
atol:float, optionalTolerance parameters passed on to isclose
copy:bool, optionalWhether to return a copy of x.
shrink:bool, optionalWhether to collapse a mask full of False to nomask.
Returns
MaskedArrayresult - The result of masking x where approximately equal to value.
def masked_where(condition, a, copy=True): (source)

Mask an array where a condition is met.

Return a as an array masked where condition is True. Any masked values of a or condition are also masked in the output.

See Also

masked_values
Mask using floating point equality.
masked_equal
Mask where equal to a given value.
masked_not_equal
Mask where not equal to a given value.
masked_less_equal
Mask where less than or equal to a given value.
masked_greater_equal
Mask where greater than or equal to a given value.
masked_less
Mask where less than a given value.
masked_greater
Mask where greater than a given value.
masked_inside
Mask inside a given interval.
masked_outside
Mask outside a given interval.
masked_invalid
Mask invalid values (NaNs or infs).

Examples

>>> import numpy.ma as ma
>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> ma.masked_where(a <= 2, a)
masked_array(data=[--, --, --, 3],
             mask=[ True,  True,  True, False],
       fill_value=999999)

Mask array b conditional on a.

>>> b = ['a', 'b', 'c', 'd']
>>> ma.masked_where(a == 2, b)
masked_array(data=['a', 'b', --, 'd'],
             mask=[False, False,  True, False],
       fill_value='N/A',
            dtype='<U1')

Effect of the copy argument.

>>> c = ma.masked_where(a <= 2, a)
>>> c
masked_array(data=[--, --, --, 3],
             mask=[ True,  True,  True, False],
       fill_value=999999)
>>> c[0] = 99
>>> c
masked_array(data=[99, --, --, 3],
             mask=[False,  True,  True, False],
       fill_value=999999)
>>> a
array([0, 1, 2, 3])
>>> c = ma.masked_where(a <= 2, a, copy=False)
>>> c[0] = 99
>>> c
masked_array(data=[99, --, --, 3],
             mask=[False,  True,  True, False],
       fill_value=999999)
>>> a
array([99,  1,  2,  3])

When condition or a contain masked values.

>>> a = np.arange(4)
>>> a = ma.masked_where(a == 2, a)
>>> a
masked_array(data=[0, 1, --, 3],
             mask=[False, False,  True, False],
       fill_value=999999)
>>> b = np.arange(4)
>>> b = ma.masked_where(b == 0, b)
>>> b
masked_array(data=[--, 1, 2, 3],
             mask=[ True, False, False, False],
       fill_value=999999)
>>> ma.masked_where(a == 3, b)
masked_array(data=[--, 1, --, --],
             mask=[ True, False,  True,  True],
       fill_value=999999)
Parameters
condition:array_likeMasking condition. When condition tests floating point values for equality, consider using masked_values instead.
a:array_likeArray to mask.
copy:boolIf True (default) make a copy of a in the result. If False modify a in place and return a view.
Returns
MaskedArrayresult - The result of masking a where condition is True.
def max(obj, axis=None, out=None, fill_value=None, keepdims=np._NoValue): (source)

Undocumented

def maximum_fill_value(obj): (source)

Return the minimum value that can be represented by the dtype of an object.

This function is useful for calculating a fill value suitable for taking the maximum of an array with a given dtype.

See Also

minimum_fill_value
The inverse function.
set_fill_value
Set the filling value of a masked array.
MaskedArray.fill_value
Return current fill value.

Examples

>>> import numpy.ma as ma
>>> a = np.int8()
>>> ma.maximum_fill_value(a)
-128
>>> a = np.int32()
>>> ma.maximum_fill_value(a)
-2147483648

An array of numeric data can also be passed.

>>> a = np.array([1, 2, 3], dtype=np.int8)
>>> ma.maximum_fill_value(a)
-128
>>> a = np.array([1, 2, 3], dtype=np.float32)
>>> ma.maximum_fill_value(a)
-inf
Parameters
obj:ndarray, dtype or scalarAn object that can be queried for it's numeric type.
Returns
scalarval - The minimum representable value.
Raises
TypeErrorIf obj isn't a suitable numeric type.
def min(obj, axis=None, out=None, fill_value=None, keepdims=np._NoValue): (source)

Undocumented

def minimum_fill_value(obj): (source)

Return the maximum value that can be represented by the dtype of an object.

This function is useful for calculating a fill value suitable for taking the minimum of an array with a given dtype.

See Also

maximum_fill_value
The inverse function.
set_fill_value
Set the filling value of a masked array.
MaskedArray.fill_value
Return current fill value.

Examples

>>> import numpy.ma as ma
>>> a = np.int8()
>>> ma.minimum_fill_value(a)
127
>>> a = np.int32()
>>> ma.minimum_fill_value(a)
2147483647

An array of numeric data can also be passed.

>>> a = np.array([1, 2, 3], dtype=np.int8)
>>> ma.minimum_fill_value(a)
127
>>> a = np.array([1, 2, 3], dtype=np.float32)
>>> ma.minimum_fill_value(a)
inf
Parameters
obj:ndarray, dtype or scalarAn object that can be queried for it's numeric type.
Returns
scalarval - The maximum representable value.
Raises
TypeErrorIf obj isn't a suitable numeric type.
def ndim(obj): (source)

maskedarray version of the numpy function.

def outer(a, b): (source)

maskedarray version of the numpy function.

def power(a, b, third=None): (source)

Returns element-wise base array raised to power from second array.

This is the masked array version of numpy.power. For details see numpy.power.

See Also

numpy.power

Notes

The out argument to numpy.power is not supported, third has to be None.

Examples

>>> import numpy.ma as ma
>>> x = [11.2, -3.973, 0.801, -1.41]
>>> mask = [0, 0, 0, 1]
>>> masked_x = ma.masked_array(x, mask)
>>> masked_x
masked_array(data=[11.2, -3.973, 0.801, --],
         mask=[False, False, False,  True],
   fill_value=1e+20)
>>> ma.power(masked_x, 2)
masked_array(data=[125.43999999999998, 15.784728999999999,
               0.6416010000000001, --],
         mask=[False, False, False,  True],
   fill_value=1e+20)
>>> y = [-0.5, 2, 0, 17]
>>> masked_y = ma.masked_array(y, mask)
>>> masked_y
masked_array(data=[-0.5, 2.0, 0.0, --],
         mask=[False, False, False,  True],
   fill_value=1e+20)
>>> ma.power(masked_x, masked_y)
masked_array(data=[0.29880715233359845, 15.784728999999999, 1.0, --],
         mask=[False, False, False,  True],
   fill_value=1e+20)
def ptp(obj, axis=None, out=None, fill_value=None, keepdims=np._NoValue): (source)

Undocumented

def put(a, indices, values, mode='raise'): (source)

Set storage-indexed locations to corresponding values.

This function is equivalent to MaskedArray.put, see that method for details.

See Also

MaskedArray.put

def putmask(a, mask, values): (source)

Changes elements of an array based on conditional and input values.

This is the masked array version of numpy.putmask, for details see numpy.putmask.

See Also

numpy.putmask

Notes

Using a masked array as values will not transform a ndarray into a MaskedArray.

def reshape(a, new_shape, order='C'): (source)

Returns an array containing the same data with a new shape.

Refer to MaskedArray.reshape for full documentation.

See Also

MaskedArray.reshape
equivalent function
def resize(x, new_shape): (source)

Return a new masked array with the specified size and shape.

This is the masked equivalent of the numpy.resize function. The new array is filled with repeated copies of x (in the order that the data are stored in memory). If x is masked, the new array will be masked, and the new mask will be a repetition of the old one.

See Also

numpy.resize
Equivalent function in the top level NumPy module.

Examples

>>> import numpy.ma as ma
>>> a = ma.array([[1, 2] ,[3, 4]])
>>> a[0, 1] = ma.masked
>>> a
masked_array(
  data=[[1, --],
        [3, 4]],
  mask=[[False,  True],
        [False, False]],
  fill_value=999999)
>>> np.resize(a, (3, 3))
masked_array(
  data=[[1, 2, 3],
        [4, 1, 2],
        [3, 4, 1]],
  mask=False,
  fill_value=999999)
>>> ma.resize(a, (3, 3))
masked_array(
  data=[[1, --, 3],
        [4, 1, --],
        [3, 4, 1]],
  mask=[[False,  True, False],
        [False, False,  True],
        [False, False, False]],
  fill_value=999999)

A MaskedArray is always returned, regardless of the input type.

>>> a = np.array([[1, 2] ,[3, 4]])
>>> ma.resize(a, (3, 3))
masked_array(
  data=[[1, 2, 3],
        [4, 1, 2],
        [3, 4, 1]],
  mask=False,
  fill_value=999999)
def right_shift(a, n): (source)

Shift the bits of an integer to the right.

This is the masked array version of numpy.right_shift, for details see that function.

See Also

numpy.right_shift

def round_(a, decimals=0, out=None): (source)

Return a copy of a, rounded to 'decimals' places.

When 'decimals' is negative, it specifies the number of positions to the left of the decimal point. The real and imaginary parts of complex numbers are rounded separately. Nothing is done if the array is not of float type and 'decimals' is greater than or equal to 0.

Notes

If out is given and does not have a mask attribute, the mask of a is lost!

Examples

>>> import numpy.ma as ma
>>> x = [11.2, -3.973, 0.801, -1.41]
>>> mask = [0, 0, 0, 1]
>>> masked_x = ma.masked_array(x, mask)
>>> masked_x
masked_array(data=[11.2, -3.973, 0.801, --],
             mask=[False, False, False, True],
    fill_value=1e+20)
>>> ma.round_(masked_x)
masked_array(data=[11.0, -4.0, 1.0, --],
             mask=[False, False, False, True],
    fill_value=1e+20)
>>> ma.round(masked_x, decimals=1)
masked_array(data=[11.2, -4.0, 0.8, --],
             mask=[False, False, False, True],
    fill_value=1e+20)
>>> ma.round_(masked_x, decimals=-1)
masked_array(data=[10.0, -0.0, 0.0, --],
             mask=[False, False, False, True],
    fill_value=1e+20)
Parameters
aUndocumented
decimals:intNumber of decimals to round to. May be negative.
out:array_likeExisting array to use for output. If not given, returns a default copy of a.
def set_fill_value(a, fill_value): (source)

Set the filling value of a, if a is a masked array.

This function changes the fill value of the masked array a in place. If a is not a masked array, the function returns silently, without doing anything.

See Also

maximum_fill_value
Return the default fill value for a dtype.
MaskedArray.fill_value
Return current fill value.
MaskedArray.set_fill_value
Equivalent method.

Examples

>>> import numpy.ma as ma
>>> a = np.arange(5)
>>> a
array([0, 1, 2, 3, 4])
>>> a = ma.masked_where(a < 3, a)
>>> a
masked_array(data=[--, --, --, 3, 4],
             mask=[ True,  True,  True, False, False],
       fill_value=999999)
>>> ma.set_fill_value(a, -999)
>>> a
masked_array(data=[--, --, --, 3, 4],
             mask=[ True,  True,  True, False, False],
       fill_value=-999)

Nothing happens if a is not a masked array.

>>> a = list(range(5))
>>> a
[0, 1, 2, 3, 4]
>>> ma.set_fill_value(a, 100)
>>> a
[0, 1, 2, 3, 4]
>>> a = np.arange(5)
>>> a
array([0, 1, 2, 3, 4])
>>> ma.set_fill_value(a, 100)
>>> a
array([0, 1, 2, 3, 4])
Parameters
a:array_likeInput array.
fill_value:dtypeFilling value. A consistency test is performed to make sure the value is compatible with the dtype of a.
Returns
NoneNothing returned by this function.
def shape(obj): (source)

maskedarray version of the numpy function.

def size(obj, axis=None): (source)

maskedarray version of the numpy function.

def sort(a, axis=-1, kind=None, order=None, endwith=True, fill_value=None): (source)

Return a sorted copy of the masked array.

Equivalent to creating a copy of the array and applying the MaskedArray sort() method.

Refer to MaskedArray.sort for the full documentation

See Also

MaskedArray.sort
equivalent method
def take(a, indices, axis=None, out=None, mode='raise'): (source)
def transpose(a, axes=None): (source)

Permute the dimensions of an array.

This function is exactly equivalent to numpy.transpose.

See Also

numpy.transpose
Equivalent function in top-level NumPy module.

Examples

>>> import numpy.ma as ma
>>> x = ma.arange(4).reshape((2,2))
>>> x[1, 1] = ma.masked
>>> x
masked_array(
  data=[[0, 1],
        [2, --]],
  mask=[[False, False],
        [False,  True]],
  fill_value=999999)
>>> ma.transpose(x)
masked_array(
  data=[[0, 2],
        [1, --]],
  mask=[[False, False],
        [False,  True]],
  fill_value=999999)
def where(condition, x=_NoValue, y=_NoValue): (source)

Return a masked array with elements from x or y, depending on condition.

Note

When only condition is provided, this function is identical to nonzero. The rest of this documentation covers only the case where all three arguments are provided.

See Also

numpy.where
Equivalent function in the top-level NumPy module.
nonzero
The function that is called when x and y are omitted

Examples

>>> x = np.ma.array(np.arange(9.).reshape(3, 3), mask=[[0, 1, 0],
...                                                    [1, 0, 1],
...                                                    [0, 1, 0]])
>>> x
masked_array(
  data=[[0.0, --, 2.0],
        [--, 4.0, --],
        [6.0, --, 8.0]],
  mask=[[False,  True, False],
        [ True, False,  True],
        [False,  True, False]],
  fill_value=1e+20)
>>> np.ma.where(x > 5, x, -3.1416)
masked_array(
  data=[[-3.1416, --, -3.1416],
        [--, -3.1416, --],
        [6.0, --, 8.0]],
  mask=[[False,  True, False],
        [ True, False,  True],
        [False,  True, False]],
  fill_value=1e+20)
Parameters
condition:array_like, boolWhere True, yield x, otherwise yield y.
x:array_like, optionalValues from which to choose. x, y and condition need to be broadcastable to some shape.
y:array_like, optionalValues from which to choose. x, y and condition need to be broadcastable to some shape.
Returns
MaskedArrayout - An masked array with masked elements where the condition is masked, elements from x where condition is True, and elements from y elsewhere.

Undocumented

absolute = (source)

Undocumented

Undocumented

Undocumented

Undocumented

Undocumented

Undocumented

anomalies = (source)

Undocumented

Undocumented

Undocumented

Undocumented

Undocumented

Undocumented

Undocumented

Undocumented

Undocumented

Undocumented

Undocumented

Undocumented

Undocumented

bitwise_and = (source)

Undocumented

bitwise_or = (source)

Undocumented

bitwise_xor = (source)

Undocumented

Undocumented

Undocumented

compress = (source)

Undocumented

conjugate = (source)

Undocumented

Undocumented

Undocumented

Undocumented

Undocumented

Undocumented

Undocumented

default_filler: dict = (source)

Undocumented

diagonal = (source)

Undocumented

Undocumented

Undocumented

Undocumented

empty_like = (source)

Undocumented

Undocumented

Undocumented

Undocumented

float_types_list = (source)

Undocumented

Undocumented

floor_divide = (source)

Undocumented

Undocumented

frombuffer = (source)

Undocumented

fromfunction = (source)

Undocumented

Undocumented

greater_equal = (source)

Undocumented

harden_mask = (source)

Undocumented

Undocumented

identity = (source)

Undocumented

Undocumented

Undocumented

Undocumented

less_equal = (source)

Undocumented

Undocumented

Undocumented

Undocumented

logical_and = (source)

Undocumented

logical_not = (source)

Undocumented

logical_or = (source)

Undocumented

logical_xor = (source)

Undocumented

Undocumented

masked_print_option = (source)

Undocumented

masked_singleton = (source)

Undocumented

Undocumented

Undocumented

Undocumented

Undocumented

multiply = (source)

Undocumented

negative = (source)

Undocumented

Undocumented

Undocumented

not_equal = (source)

Undocumented

Undocumented

ones_like = (source)

Undocumented

Undocumented

Undocumented

Undocumented

remainder = (source)

Undocumented

Undocumented

shrink_mask = (source)

Undocumented

Undocumented

Undocumented

soften_mask = (source)

Undocumented

Undocumented

Undocumented

Undocumented

subtract = (source)

Undocumented

Undocumented

swapaxes = (source)

Undocumented

Undocumented

Undocumented

Undocumented

true_divide = (source)

Undocumented

ufunc_domain: dict = (source)

Undocumented

ufunc_fills: dict = (source)

Undocumented

Undocumented

Undocumented

zeros_like = (source)

Undocumented

def _arraymethod(funcname, onmask=True): (source)

Return a class method wrapper around a basic array method.

Creates a class method which returns a masked array, where the new _data array is the output of the corresponding basic method called on the original _data.

If onmask is True, the new mask is the output of the method called on the initial mask. Otherwise, the new mask is just a reference to the initial mask.

Parameters
funcname:strName of the function to apply on data.
onmask:boolWhether the mask must be processed also (True) or left alone (False). Default is True. Make available as _onmask attribute.
Returns
instancemethodmethod - Class method wrapper of the specified basic array method.
def _check_fill_value(fill_value, ndtype): (source)

Private function validating the given fill_value for the given dtype.

If fill_value is None, it is set to the default corresponding to the dtype.

If fill_value is not None, its value is forced to the given dtype.

The result is always a 0d array.

def _check_mask_axis(mask, axis, keepdims=np._NoValue): (source)

Check whether there are masked values along the given axis

def _convolve_or_correlate(f, a, v, mode, propagate_mask): (source)

Helper function for ma.correlate and ma.convolve

def _deprecate_argsort_axis(arr): (source)

Adjust the axis passed to argsort, warning if necessary

Parameters
arrThe array which argsort was called on
np.ma.argsort has a long-term bug where the default of the axis argument
is wrong (gh-8701)
which now must be kept for backwards compatibility.
Thankfully
this only makes a difference when arrays are 2- or more-
dimensional
so we only need a warning then.
def _extremum_fill_value(obj, extremum, extremum_name): (source)

Undocumented

def _get_dtype_of(obj): (source)

Convert the argument for *_fill_value into a dtype

def _mareconstruct(subtype, baseclass, baseshape, basetype): (source)

Internal function that builds a new MaskedArray from the information stored in a pickle.

def _recursive_fill_value(dtype, f): (source)

Recursively produce a fill value for dtype, calling f on scalar dtypes

def _recursive_filled(a, mask, fill_value): (source)

Recursively fill a with fill_value.

def _recursive_mask_or(m1, m2, newmask): (source)

Undocumented

def _recursive_printoption(result, mask, printopt): (source)

Puts printoptions in result where mask is True.

Private function allowing for recursion

def _recursive_set_fill_value(fillvalue, dt): (source)

Create a fill value for a structured dtype.

Parameters
fillvalue:scalar or array_likeScalar or array representing the fill value. If it is of shorter length than the number of fields in dt, it will be resized.
dt:dtypeThe structured dtype for which to create the fill value.
Returns
tupleval - A tuple of values corresponding to the structured fill value.
def _replace_dtype_fields(dtype, primitive_dtype): (source)

Construct a dtype description list from a given dtype.

Returns a new dtype object, with all fields and subtypes in the given type recursively replaced with primitive_dtype.

Arguments are coerced to dtypes first.

def _replace_dtype_fields_recursive(dtype, primitive_dtype): (source)

Private function allowing recursion in _replace_dtype_fields.

def _shrink_mask(m): (source)

Shrink a mask to nomask if possible

_legacy_print_templates = (source)

Undocumented