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)
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 _​Domain​Check​Interval Define a valid interval, so that :
Class _​Domained​Binary​Operation Define binary operations that have a domain, like divide.
Class _​Domain​Greater DomainGreater(v)(x) is True where x <= v.
Class _​Domain​Greater​Equal DomainGreaterEqual(v)(x) is True where x < v.
Class _​Domain​Safe​Divide Define a domain for safe division.
Class _​Domain​Tan 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 _​Masked​Binary​Operation Define masked version of binary operations, where invalid values are pre-masked.
Class _​Masked​Print​Option Handle the string used to represent missing data in a masked array.
Class _​Masked​UFunc Undocumented
Class _​Masked​Unary​Operation Defines masked version of unary operations, where invalid values are pre-masked.
Class ​MAError Class for masked array related errors.
Class ​Masked​Array An array class with possibly masked values.
Class ​Masked​Array​Future​Warning Undocumented
Class ​Masked​Constant No class docstring; 0/1 class variable, 2/13 methods, 0/1 class method documented
Class ​Masked​Iterator Flat iterator object to iterate over masked arrays.
Class ​Mask​Error Class for mask related errors.
Class mvoid Fake a 'void' object to use for masked array with structured dtypes.
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 ​_pickle​_warn Undocumented
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
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 is​Masked​Array 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
Function transpose Permute the dimensions of an array.
Function where Return a masked array with elements from x or y, depending on condition.
Variable ​_legacy​_print​_templates Undocumented
abs =

Undocumented

absolute =

Undocumented

add =

Undocumented

all =

Undocumented

alltrue =

Undocumented

angle =

Undocumented

anom =

Undocumented

anomalies =

Undocumented

any =

Undocumented

arange =

Undocumented

arccos =

Undocumented

arccosh =

Undocumented

arcsin =

Undocumented

arcsinh =

Undocumented

arctan =

Undocumented

arctan2 =

Undocumented

arctanh =

Undocumented

argmax =

Undocumented

argmin =

Undocumented

around =

Undocumented

bitwise_and =

Undocumented

bitwise_or =

Undocumented

bitwise_xor =

Undocumented

ceil =

Undocumented

clip =

Undocumented

compress =

Undocumented

conjugate =

Undocumented

copy =

Undocumented

cos =

Undocumented

cosh =

Undocumented

count =

Undocumented

cumprod =

Undocumented

cumsum =

Undocumented

default_filler: dict =

Undocumented

diagonal =

Undocumented

diff =

Undocumented

divide =

Undocumented

empty =

Undocumented

empty_like =

Undocumented

equal =

Undocumented

exp =

Undocumented

fabs =

Undocumented

float_types_list =

Undocumented

floor =

Undocumented

floor_divide =

Undocumented

fmod =

Undocumented

frombuffer =

Undocumented

fromfunction =

Undocumented

greater =

Undocumented

greater_equal =

Undocumented

harden_mask =

Undocumented

hypot =

Undocumented

identity =

Undocumented

ids =

Undocumented

indices =

Undocumented

less =

Undocumented

less_equal =

Undocumented

log =

Undocumented

log10 =

Undocumented

log2 =

Undocumented

logical_and =

Undocumented

logical_not =

Undocumented

logical_or =

Undocumented

logical_xor =

Undocumented

masked =

Undocumented

masked_print_option =

Undocumented

masked_singleton =

Undocumented

maximum =

Undocumented

mean =

Undocumented

minimum =

Undocumented

mod =

Undocumented

multiply =

Undocumented

negative =

Undocumented

nomask =

Undocumented

nonzero =

Undocumented

not_equal =

Undocumented

ones =

Undocumented

ones_like =

Undocumented

prod =

Undocumented

product =

Undocumented

ravel =

Undocumented

remainder =

Undocumented

repeat =

Undocumented

shrink_mask =

Undocumented

sin =

Undocumented

sinh =

Undocumented

soften_mask =

Undocumented

sqrt =

Undocumented

squeeze =

Undocumented

std =

Undocumented

subtract =

Undocumented

sum =

Undocumented

swapaxes =

Undocumented

tan =

Undocumented

tanh =

Undocumented

trace =

Undocumented

true_divide =

Undocumented

ufunc_domain: dict =

Undocumented

ufunc_fills: dict =

Undocumented

var =

Undocumented

zeros =

Undocumented

zeros_like =

Undocumented

def _arraymethod(funcname, onmask=True):

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 : str
Name of the function to apply on data.
onmask : bool
Whether the mask must be processed also (True) or left alone (False). Default is True. Make available as _onmask attribute.

Returns

method : instancemethod
Class method wrapper of the specified basic array method.
def _check_fill_value(fill_value, ndtype):

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):
Check whether there are masked values along the given axis
def _convolve_or_correlate(f, a, v, mode, propagate_mask):
Helper function for ma.correlate and ma.convolve
def _deprecate_argsort_axis(arr):

Adjust the axis passed to argsort, warning if necessary

Parameters

arr
The 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):

Undocumented

def _get_dtype_of(obj):
Convert the argument for *_fill_value into a dtype
def _mareconstruct(subtype, baseclass, baseshape, basetype):
Internal function that builds a new MaskedArray from the information stored in a pickle.
def _pickle_warn(method):

Undocumented

def _recursive_fill_value(dtype, f):
Recursively produce a fill value for dtype, calling f on scalar dtypes
def _recursive_filled(a, mask, fill_value):
Recursively fill a with fill_value.
def _recursive_mask_or(m1, m2, newmask):

Undocumented

def _recursive_printoption(result, mask, printopt):

Puts printoptions in result where mask is True.

Private function allowing for recursion

def _recursive_set_fill_value(fillvalue, dt):

Create a fill value for a structured dtype.

Parameters

fillvalue : scalar or array_like
Scalar or array representing the fill value. If it is of shorter length than the number of fields in dt, it will be resized.
dt : dtype
The structured dtype for which to create the fill value.

Returns

val: tuple
A tuple of values corresponding to the structured fill value.
def _replace_dtype_fields(dtype, primitive_dtype):

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):
Private function allowing recursion in _replace_dtype_fields.
def _shrink_mask(m):
Shrink a mask to nomask if possible
def allclose(a, b, masked_equal=True, rtol=1e-05, atol=1e-08):

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.

Parameters

a, b : array_like
Input arrays to compare.
masked_equal : bool, optional
Whether masked values in a and b are considered equal (True) or not (False). They are considered equal by default.
rtol : float, optional
Relative tolerance. The relative difference is equal to rtol * b. Default is 1e-5.
atol : float, optional
Absolute tolerance. The absolute difference is equal to atol. Default is 1e-8.

Returns

y : bool
Returns True if the two arrays are equal within the given tolerance, False otherwise. If either array contains NaN, then False is returned.

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
def allequal(a, b, fill_value=True):

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

Parameters

a, b : array_like
Input arrays to compare.
fill_value : bool, optional
Whether masked values in a or b are considered equal (True) or not (False).

Returns

y : bool
Returns True if the two arrays are equal within the given tolerance, False otherwise. If either array contains NaN, then False is returned.

See Also

all, any numpy.ma.allclose

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
def append(a, b, axis=None):

Append values to the end of an array.

New in version 1.9.0.

Parameters

a : array_like
Values are appended to a copy of this array.
b : array_like
These 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, optional
The axis along which v are appended. If axis is not given, both a and b are flattened before use.

Returns

append : MaskedArray
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.

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)
def argsort(a, axis=np._NoValue, kind=None, order=None, endwith=True, fill_value=None):
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):

Shortcut to MaskedArray.

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

def asanyarray(a, dtype=None):

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.

Parameters

a : array_like
Input data, in any form that can be converted to an array.
dtype : dtype, optional
By default, the data-type is inferred from the input data.
order : {'C', 'F'}, optional
Whether to use row-major ('C') or column-major ('FORTRAN') memory representation. Default is 'C'.

Returns

out : MaskedArray
MaskedArray interpretation of a.

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'>
def asarray(a, dtype=None, order=None):

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.

Parameters

a : array_like
Input 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, optional
By default, the data-type is inferred from the input data.
order : {'C', 'F'}, optional
Whether to use row-major ('C') or column-major ('FORTRAN') memory representation. Default is 'C'.

Returns

out : MaskedArray
Masked array interpretation of a.

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'>
def choose(indices, choices, out=None, mode='raise'):

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.

Parameters

indices : ndarray of ints
This array must contain integers in [0, n-1], where n is the number of choices.
choices : sequence of arrays
Choice arrays. The index array and all of the choices should be broadcastable to the same shape.
out : array, optional
If 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

merged_array : array

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)
def common_fill_value(a, b):

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.

Parameters

a, b : MaskedArray
The masked arrays for which to compare fill values.

Returns

fill_value : scalar or None
The common fill value, or 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
def compressed(x):

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):

Concatenate a sequence of arrays along the given axis.

Parameters

arrays : sequence of array_like
The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).
axis : int, optional
The axis along which the arrays will be joined. Default is 0.

Returns

result : MaskedArray
The concatenated array with any masked entries preserved.

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)
def convolve(a, v, mode='full', propagate_mask=True):

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

Parameters

a, v : array_like
Input sequences.
mode : {'valid', 'same', 'full'}, optional
Refer to the np.convolve docstring.
propagate_mask : bool
If 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

out : MaskedArray
Discrete, linear convolution of a and v.

See Also

numpy.convolve : Equivalent function in the top-level NumPy module.

def correlate(a, v, mode='valid', propagate_mask=True):

Cross-correlation of two 1-dimensional sequences.

Parameters

a, v : array_like
Input sequences.
mode : {'valid', 'same', 'full'}, optional
Refer to the np.convolve docstring. Note that the default is 'valid', unlike convolve, which uses 'full'.
propagate_mask : bool
If 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

out : MaskedArray
Discrete cross-correlation of a and v.

See Also

numpy.correlate : Equivalent function in the top-level NumPy module.

def default_fill_value(obj):

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.

Parameters

obj : ndarray, dtype or scalar
The array data-type or scalar for which the default fill value is returned.

Returns

fill_value : scalar
The default 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)
def diag(v, k=0):

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):
Adds a Notes section to an existing docstring.
def filled(a, fill_value=None):

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.

Parameters

a : MaskedArray or array_like
An 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

a : ndarray
The filled array.

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]])
def fix_invalid(a, mask=nomask, copy=True, fill_value=None):

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

Invalid data means values of nan, inf, etc.

Parameters

a : array_like
Input array, a (subclass of) ndarray.
mask : sequence, optional
Mask. Must be convertible to an array of booleans with the same shape as data. True indicates a masked (i.e. invalid) data.
copy : bool, optional
Whether to use a copy of a (True) or to fix a in place (False). Default is True.
fill_value : scalar, optional
Value used for fixing invalid data. Default is None, in which case the a.fill_value is used.

Returns

b : MaskedArray
The input array with invalid entries fixed.

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])
def flatten_mask(mask):

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

Parameters

mask : array_like
Input array, which will be interpreted as booleans.

Returns

flattened_mask : ndarray of bools
The flattened input.

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])
def flatten_structured_array(a):

Flatten a structured array.

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

Parameters

a : structured array

Returns

output : masked array or ndarray
A flattened masked array if the input is a masked array, otherwise a standard ndarray.

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.]])
def fromfile(file, dtype=float, count=-1, sep=''):

Undocumented

def fromflex(fxarray):

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.

Parameters

fxarray : ndarray
The structured input array, containing _data and _mask fields. If present, other fields are discarded.

Returns

result : MaskedArray
The constructed masked array.

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)
def get_fill_value(a):
Return the filling value of a, if any. Otherwise, returns the default filling value for that type.
def get_masked_subclass(*arrays):

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):
Get the signature from obj
def getdata(a, subok=True):

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.

Parameters

a : array_like
Input MaskedArray, alternatively a ndarray or a subclass thereof.
subok : bool
Whether to force the output to be a pure ndarray (False) or to return a subclass of ndarray if appropriate (True, default).

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]])
def getmask(a):

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.

Parameters

a : array_like
Input MaskedArray for which the mask is required.

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
def getmaskarray(arr):

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.

Parameters

arr : array_like
Input MaskedArray for which the mask is required.

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]])
def inner(a, b):

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):

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.

Parameters

m : array_like
Array to test.

Returns

result : bool
True if m.dtype.type is MaskType, False otherwise.

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
def is_masked(x):

Determine whether input has masked values.

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

Parameters

x : array_like
Array to check for masked values.

Returns

result : bool
True if x is a MaskedArray with masked values, False otherwise.

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
def is_string_or_list_of_strings(val):

Undocumented

def isMaskedArray(x):

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.

Parameters

x : object
Object to test.

Returns

result : bool
True if x is a MaskedArray.

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
def left_shift(a, n):

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):

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.

Parameters

m : array_like
Potential mask.
copy : bool, optional
Whether to return a copy of m (True) or m itself (False).
shrink : bool, optional
Whether to shrink m to nomask if all its values are False.
dtype : dtype, optional
Data-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

result : ndarray
A boolean mask derived from m.

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')])
def make_mask_descr(ndtype):

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.

Parameters

ndtype : dtype
The dtype to convert.

Returns

result : dtype
A dtype that looks like ndtype, the type of all fields is boolean.

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')
def make_mask_none(newshape, dtype=None):

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.

Parameters

newshape : tuple
A tuple indicating the shape of the mask.
dtype : {None, dtype}, optional
If None, use a MaskType instance. Otherwise, use a new datatype with the same fields as dtype, converted to boolean types.

Returns

result : ndarray
An ndarray of appropriate shape and dtype, filled with False.

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')])
def mask_or(m1, m2, copy=False, shrink=True):

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).

Parameters

m1, m2 : array_like
Input masks.
copy : bool, optional
If copy is False and one of the inputs is nomask, return a view of the other input mask. Defaults to False.
shrink : bool, optional
Whether to shrink the output to nomask if all its values are False. Defaults to True.

Returns

mask : output mask
The result masks values that are masked in either m1 or m2.

Raises

ValueError
If m1 and m2 have different flexible dtypes.

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])
def masked_equal(x, value, copy=True):

Mask an array where equal to a given value.

This function is a shortcut to masked_where, with condition = (x == 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):

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):

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):

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):

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):

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):

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):

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):

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.

Parameters

x : array_like
Array to mask
value : object
Comparison value
copy : {True, False}, optional
Whether to return a copy of x.
shrink : {True, False}, optional
Whether to collapse a mask full of False to nomask

Returns

result : MaskedArray
The result of masking x where equal to value.

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)
def masked_outside(x, v1, v2, copy=True):

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):

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.

Parameters

x : array_like
Array to mask.
value : float
Masking value.
rtol, atol : float, optional
Tolerance parameters passed on to isclose
copy : bool, optional
Whether to return a copy of x.
shrink : bool, optional
Whether to collapse a mask full of False to nomask.

Returns

result : MaskedArray
The result of masking x where approximately equal to value.

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, 1.5)
masked_array(data=[1. , 1.1, 2. , 1.1, 3. ],
             mask=False,
       fill_value=1.5)

For integers, the fill value will be different in general to the result of masked_equal.

>>> x = np.arange(5)
>>> x
array([0, 1, 2, 3, 4])
>>> ma.masked_values(x, 2)
masked_array(data=[0, 1, --, 3, 4],
             mask=[False, False,  True, False, False],
       fill_value=2)
>>> ma.masked_equal(x, 2)
masked_array(data=[0, 1, --, 3, 4],
             mask=[False, False,  True, False, False],
       fill_value=2)
def masked_where(condition, a, copy=True):

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.

Parameters

condition : array_like
Masking condition. When condition tests floating point values for equality, consider using masked_values instead.
a : array_like
Array to mask.
copy : bool
If True (default) make a copy of a in the result. If False modify a in place and return a view.

Returns

result : MaskedArray
The result of masking a where condition is True.

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)
def max(obj, axis=None, out=None, fill_value=None, keepdims=np._NoValue):

Undocumented

def maximum_fill_value(obj):

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.

Parameters

obj : ndarray, dtype or scalar
An object that can be queried for it's numeric type.

Returns

val : scalar
The minimum representable value.

Raises

TypeError
If obj isn't a suitable numeric type.

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
def min(obj, axis=None, out=None, fill_value=None, keepdims=np._NoValue):

Undocumented

def minimum_fill_value(obj):

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.

Parameters

obj : ndarray, dtype or scalar
An object that can be queried for it's numeric type.

Returns

val : scalar
The maximum representable value.

Raises

TypeError
If obj isn't a suitable numeric type.

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
def ndim(obj):
maskedarray version of the numpy function.
def outer(a, b):
maskedarray version of the numpy function.
def power(a, b, third=None):

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.

def ptp(obj, axis=None, out=None, fill_value=None, keepdims=np._NoValue):

Undocumented

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

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):

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'):

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):

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):

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):

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.

Parameters

decimals : int
Number of decimals to round to. May be negative.
out : array_like
Existing array to use for output. If not given, returns a default copy of a.

Notes

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

def set_fill_value(a, fill_value):

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.

Parameters

a : array_like
Input array.
fill_value : dtype
Filling value. A consistency test is performed to make sure the value is compatible with the dtype of a.

Returns

None
Nothing returned by this function.

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])
def shape(obj):
maskedarray version of the numpy function.
def size(obj, axis=None):
maskedarray version of the numpy function.
def sort(a, axis=-1, kind=None, order=None, endwith=True, fill_value=None):

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'):
def transpose(a, axes=None):

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):

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.

Parameters

condition : array_like, bool
Where True, yield x, otherwise yield y.
x, y : array_like, optional
Values from which to choose. x, y and condition need to be broadcastable to some shape.

Returns

out : MaskedArray
An masked array with masked elements where the condition is masked, elements from x where condition is True, and elements from y elsewhere.

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)
_legacy_print_templates =

Undocumented