class MaskedArray(ndarray): (source)
Known subclasses: numpy.ma.core.MaskedConstant
, numpy.ma.core.mvoid
, numpy.ma.tests.test_subclassing.MSubArray
, numpy.ma.tests.test_subclassing.SubMaskedArray
, numpy.matrixlib.tests.test_masked_matrix.MMatrix
An array class with possibly masked values.
Masked values of True exclude the corresponding element from any computation.
Construction:
x = MaskedArray(data, mask=nomask, dtype=None, copy=False, subok=True, ndmin=0, fill_value=None, keep_mask=True, hard_mask=None, shrink=True, order=None)
Examples
The mask can be initialized with an array of boolean values with the same shape as data.
>>> data = np.arange(6).reshape((2, 3)) >>> np.ma.MaskedArray(data, mask=[[False, True, False], ... [False, False, True]]) masked_array( data=[[0, --, 2], [3, 4, --]], mask=[[False, True, False], [False, False, True]], fill_value=999999)
Alternatively, the mask can be initialized to homogeneous boolean array with the same shape as data by passing in a scalar boolean value:
>>> np.ma.MaskedArray(data, mask=False) masked_array( data=[[0, 1, 2], [3, 4, 5]], mask=[[False, False, False], [False, False, False]], fill_value=999999)
>>> np.ma.MaskedArray(data, mask=True) masked_array( data=[[--, --, --], [--, --, --]], mask=[[ True, True, True], [ True, True, True]], fill_value=999999, dtype=int64)
Note
The recommended practice for initializing mask with a scalar
boolean value is to use True/False rather than
np.True_/np.False_. The reason is nomask
is represented internally as np.False_.
>>> np.False_ is np.ma.nomask True
Parameters | |
data | Input data. |
mask | Mask. Must be convertible to an array of booleans with the same
shape as data . True indicates a masked (i.e. invalid) data. |
dtype | Data type of the output.
If dtype is None, the type of the data argument (data.dtype)
is used. If dtype is not None and different from data.dtype,
a copy is performed. |
copy | Whether to copy the input data (True), or to use a reference instead. Default is False. |
subok | Whether to return a subclass of MaskedArray if possible (True) or a
plain MaskedArray . Default is True. |
ndmin | Minimum number of dimensions. Default is 0. |
fill | Value used to fill in the masked values when necessary. If None, a default based on the data-type is used. |
keep | Whether to combine mask with the mask of the input data, if any
(True), or to use only mask for the output (False). Default is True. |
hard | Whether to use a hard mask or not. With a hard mask, masked values cannot be unmasked. Default is False. |
shrink | Whether to force compression of an empty mask. Default is True. |
order | Specify the order of the array. If order is 'C', then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). If order is 'A' (default), then the returned array may be in any order (either C-, Fortran-contiguous, or even discontiguous), unless a copy is required, in which case it will be C-contiguous. |
Method | __add__ |
Add self to other, and return a new masked array. |
Method | __array |
Finalizes the masked array. |
Method | __array |
Special hook for ufuncs. |
Method | __deepcopy__ |
Undocumented |
Method | __div__ |
Divide other into self, and return a new masked array. |
Method | __eq__ |
Check whether other equals self elementwise. |
Method | __float__ |
Convert to float. |
Method | __floordiv__ |
Divide other into self, and return a new masked array. |
Method | __ge__ |
Undocumented |
Method | __getitem__ |
x.__getitem__(y) <==> x[y] |
Method | __getstate__ |
Return the internal state of the masked array, for pickling purposes. |
Method | __gt__ |
Undocumented |
Method | __iadd__ |
Add other to self in-place. |
Method | __idiv__ |
Divide self by other in-place. |
Method | __ifloordiv__ |
Floor divide self by other in-place. |
Method | __imul__ |
Multiply self by other in-place. |
Method | __int__ |
Convert to int. |
Method | __ipow__ |
Raise self to the power other, in place. |
Method | __isub__ |
Subtract other from self in-place. |
Method | __itruediv__ |
True divide self by other in-place. |
Method | __le__ |
Undocumented |
Method | __lt__ |
Undocumented |
Method | __mul__ |
Multiply self by other, and return a new masked array. |
Method | __ne__ |
Check whether other does not equal self elementwise. |
Method | __new__ |
Create a new masked array from scratch. |
Method | __pow__ |
Raise self to the power other, masking the potential NaNs/Infs |
Method | __radd__ |
Add other to self, and return a new masked array. |
Method | __reduce__ |
Return a 3-tuple for pickling a MaskedArray. |
Method | __repr__ |
Literal string representation. |
Method | __rfloordiv__ |
Divide self into other, and return a new masked array. |
Method | __rmul__ |
Multiply other by self, and return a new masked array. |
Method | __rpow__ |
Raise other to the power self, masking the potential NaNs/Infs |
Method | __rsub__ |
Subtract self from other, and return a new masked array. |
Method | __rtruediv__ |
Divide self into other, and return a new masked array. |
Method | __setitem__ |
x.__setitem__(i, y) <==> x[i]=y |
Method | __setmask__ |
Set the mask. |
Method | __setstate__ |
Restore the internal state of the masked array, for pickling purposes. state is typically the output of the __getstate__ output, and is a 5-tuple: |
Method | __str__ |
Undocumented |
Method | __sub__ |
Subtract other from self, and return a new masked array. |
Method | __truediv__ |
Divide other into self, and return a new masked array. |
Method | all |
Returns True if all elements evaluate to True. |
Method | anom |
Compute the anomalies (deviations from the arithmetic mean) along the given axis. |
Method | any |
Returns True if any of the elements of a evaluate to True. |
Method | argmax |
Returns array of indices of the maximum values along the given axis. Masked values are treated as if they had the value fill_value. |
Method | argmin |
Return array of indices to the minimum values along the given axis. |
Method | argpartition |
Undocumented |
Method | argsort |
Return an ndarray of indices that sort the array along the specified axis. Masked values are filled beforehand to fill_value . |
Method | compress |
Return a where condition is True. |
Method | compressed |
Return all the non-masked data as a 1-D array. |
Method | count |
Count the non-masked elements of the array along the given axis. |
Method | cumprod |
Return the cumulative product of the array elements over the given axis. |
Method | cumsum |
Return the cumulative sum of the array elements over the given axis. |
Method | dot |
a.dot(b, out=None) |
Method | dtype |
Undocumented |
Method | fill |
Undocumented |
Method | filled |
Return a copy of self, with masked values filled with a given value. However, if there are no masked values to fill, self will be returned instead as an ndarray. |
Method | flat |
Undocumented |
Method | harden |
Force the mask to hard, preventing unmasking by assignment. |
Method | ids |
Return the addresses of the data and mask areas. |
Method | iscontiguous |
Return a boolean indicating whether the data is contiguous. |
Method | mask |
Undocumented |
Method | max |
Return the maximum along a given axis. |
Method | mean |
Returns the average of the array elements along given axis. |
Method | min |
Return the minimum along a given axis. |
Method | nonzero |
Return the indices of unmasked elements that are not zero. |
Method | partition |
Undocumented |
Method | prod |
Return the product of the array elements over the given axis. |
Method | ptp |
Return (maximum - minimum) along the given dimension (i.e. peak-to-peak value). |
Method | put |
Set storage-indexed locations to corresponding values. |
Method | ravel |
Returns a 1D version of self, as a view. |
Method | recordmask |
Undocumented |
Method | reshape |
Give a new shape to the array without changing its data. |
Method | resize |
This method does nothing, except raise a ValueError exception. A masked array does not own its data and therefore cannot safely be resized in place. Use the numpy.ma.resize function instead. |
Method | round |
Return each element rounded to the given number of decimals. |
Method | shape |
Undocumented |
Method | shrink |
Reduce a mask to nomask when possible. |
Method | soften |
Force the mask to soft (default), allowing unmasking by assignment. |
Method | sort |
Sort the array, in-place |
Method | std |
Returns the standard deviation of the array elements along given axis. |
Method | sum |
Return the sum of the array elements over the given axis. |
Method | take |
No summary |
Method | tobytes |
Return the array data as a string containing the raw bytes in the array. |
Method | tofile |
Save a masked array to a file in binary format. |
Method | toflex |
Transforms a masked array into a flexible-type array. |
Method | tolist |
Return the data portion of the masked array as a hierarchical Python list. |
Method | tostring |
A compatibility alias for tobytes , with exactly the same behavior. |
Method | trace |
(this docstring should be overwritten) |
Method | unshare |
Copy the mask and set the sharedmask flag to False. |
Method | var |
Returns the variance of the array elements along given axis. |
Method | view |
Return a view of the MaskedArray data. |
Constant | T |
Undocumented |
Class Variable | __array |
Undocumented |
Class Variable | copy |
Undocumented |
Class Variable | data |
Undocumented |
Class Variable | diagonal |
Undocumented |
Class Variable | flatten |
Undocumented |
Class Variable | repeat |
Undocumented |
Class Variable | squeeze |
Undocumented |
Class Variable | swapaxes |
Undocumented |
Class Variable | transpose |
Undocumented |
Instance Variable | fill |
The filling value of the masked array is a scalar. When setting, None will set to a default based on the data type. |
Property | baseclass |
Class of the underlying data (read-only). |
Property | dtype |
Undocumented |
Property | flat |
Return a flat iterator, or set a flattened version of self to value. |
Property | hardmask |
Specifies whether values can be unmasked through assignments. |
Property | imag |
The imaginary part of the masked array. |
Property | mask |
Current mask. |
Property | real |
The real part of the masked array. |
Property | recordmask |
Get or set the mask of the array if it has no named fields. For structured arrays, returns a ndarray of booleans where entries are True if all the fields are masked, False otherwise: |
Property | shape |
Undocumented |
Property | sharedmask |
Share status of the mask (read-only). |
Method | _comparison |
Compare self with other using operator.eq or operator.ne. |
Method | _delegate |
Undocumented |
Method | _get |
Returns the underlying data, as a view of the masked array. |
Method | _insert |
Replace masked values with masked_print_option, casting all innermost dtypes to object. |
Method | _update |
Copies some attributes of obj to self. |
Class Variable | _data |
Undocumented |
Class Variable | _defaulthardmask |
Undocumented |
Class Variable | _print |
Undocumented |
Class Variable | _print |
Undocumented |
Instance Variable | _fill |
Undocumented |
Instance Variable | _hardmask |
Undocumented |
Instance Variable | _mask |
Undocumented |
Instance Variable | _sharedmask |
Undocumented |
numpy.ma.core.MaskedConstant
Special hook for ufuncs.
Wraps the numpy array and sets the mask according to context.
Check whether other equals self elementwise.
When either of the elements is masked, the result is masked as well, but the underlying boolean data are still set, with self and other considered equal if both are masked, and unequal otherwise.
For structured arrays, all fields are combined, with masked values ignored. The result is masked if all fields were masked, with self and other considered equal only if both were fully masked.
numpy.ma.core.mvoid
x.__getitem__(y) <==> x[y]
Return the item described by i, as a masked array.
Check whether other does not equal self elementwise.
When either of the elements is masked, the result is masked as well, but the underlying boolean data are still set, with self and other considered equal if both are masked, and unequal otherwise.
For structured arrays, all fields are combined, with masked values ignored. The result is masked if all fields were masked, with self and other considered equal only if both were fully masked.
numpy.ma.core.MaskedConstant
, numpy.ma.core.mvoid
, numpy.ma.tests.test_subclassing.MSubArray
, numpy.ma.tests.test_subclassing.SubMaskedArray
, numpy.matrixlib.tests.test_masked_matrix.MMatrix
Create a new masked array from scratch.
Notes
A masked array can also be created by taking a .view(MaskedArray).
numpy.ma.core.mvoid
x.__setitem__(i, y) <==> x[i]=y
Set item described by index. If value is masked, masks those locations.
Restore the internal state of the masked array, for pickling purposes. state is typically the output of the __getstate__ output, and is a 5-tuple:
- class name
- a tuple giving the shape of the data
- a typecode for the data
- a binary string for the data
- a binary string for the mask.
Returns True if all elements evaluate to True.
The output array is masked where all the values along the given axis
are masked: if the output would have been a scalar and that all the
values are masked, then the output is masked
.
Refer to numpy.all
for full documentation.
See Also
numpy.ndarray.all
- corresponding function for ndarrays
numpy.all
- equivalent function
Examples
>>> np.ma.array([1,2,3]).all() True >>> a = np.ma.array([1,2,3], mask=True) >>> (a.all() is np.ma.masked) True
Compute the anomalies (deviations from the arithmetic mean) along the given axis.
Returns an array of anomalies, with the same shape as the input and where the arithmetic mean is computed along the given axis.
See Also
mean
- Compute the mean of the array.
Examples
>>> a = np.ma.array([1,2,3]) >>> a.anom() masked_array(data=[-1., 0., 1.], mask=False, fill_value=1e+20)
Parameters | |
axis:int , optional | Axis over which the anomalies are taken. The default is to use the mean of the flattened array as reference. |
dtype:dtype , optional |
|
Returns True if any of the elements of a
evaluate to True.
Masked values are considered as False during computation.
Refer to numpy.any
for full documentation.
See Also
numpy.ndarray.any
- corresponding function for ndarrays
numpy.any
- equivalent function
Returns array of indices of the maximum values along the given axis. Masked values are treated as if they had the value fill_value.
Examples
>>> a = np.arange(6).reshape(2,3) >>> a.argmax() 5 >>> a.argmax(0) array([1, 1, 1]) >>> a.argmax(1) array([2, 2])
Parameters | |
axis:{None, integer} | If None, the index is into the flattened array, otherwise along the specified axis |
fillscalar or None , optional | Value used to fill in the masked values. If None, the output of maximum_fill_value(self._data) is used instead. |
out:{None, array}, optional | Array into which the result can be placed. Its type is preserved and it must be of the right shape to hold the output. |
keepdims | Undocumented |
Returns | |
{integer_array} | index_array |
Return array of indices to the minimum values along the given axis.
Examples
>>> x = np.ma.array(np.arange(4), mask=[1,1,0,0]) >>> x.shape = (2,2) >>> x masked_array( data=[[--, --], [2, 3]], mask=[[ True, True], [False, False]], fill_value=999999) >>> x.argmin(axis=0, fill_value=-1) array([0, 0]) >>> x.argmin(axis=0, fill_value=9) array([1, 1])
Parameters | |
axis:{None, integer} | If None, the index is into the flattened array, otherwise along the specified axis |
fillscalar or None , optional | Value used to fill in the masked values. If None, the output of minimum_fill_value(self._data) is used instead. |
out:{None, array}, optional | Array into which the result can be placed. Its type is preserved and it must be of the right shape to hold the output. |
keepdims | Undocumented |
Returns | |
ndarray or scalar | If multi-dimension input, returns a new ndarray of indices to the minimum values along the given axis. Otherwise, returns a scalar of index to the minimum values along the given axis. |
Return an ndarray of indices that sort the array along the
specified axis. Masked values are filled beforehand to
fill_value
.
See Also
ma.MaskedArray.sort
- Describes sorting algorithms used.
lexsort
- Indirect stable sort with multiple keys.
numpy.ndarray.sort
- Inplace sort.
Notes
See sort
for notes on the different sorting algorithms.
Examples
>>> a = np.ma.array([3,2,1], mask=[False, False, True]) >>> a masked_array(data=[3, 2, --], mask=[False, False, True], fill_value=999999) >>> a.argsort() array([1, 0, 2])
Parameters | |
axis:int , optional | Axis along which to sort. If None, the default, the flattened array is used.
Changed in version 1.13.0: Previously, the default was documented to be -1, but that was
in error. At some future date, the default will change to -1, as
originally intended.
Until then, the axis should be given explicitly when
arr.ndim > 1, to avoid a FutureWarning.
|
kind:{'quicksort', 'mergesort', 'heapsort', 'stable'}, optional | The sorting algorithm used. |
order:list , optional | When a is an array with fields defined, this argument specifies
which fields to compare first, second, etc. Not all fields need be
specified. |
endwith:{True, False}, optional | Whether missing values (if any) should be treated as the largest values (True) or the smallest values (False) When the array contains unmasked values at the same extremes of the datatype, the ordering of these values and the masked values is undefined. |
fillscalar or None , optional | Value used internally for the masked values. If fill_value is not None, it supersedes endwith. |
Returns | |
ndarray , int | index_array - Array of indices that sort a along the specified axis.
In other words, a[index_array] yields a sorted a . |
Return a
where condition is True.
If condition is a ~ma.MaskedArray
, missing values are considered
as False.
Notes
Please note the difference with compressed
!
The output of compress
has a mask, the output of
compressed
does not.
Examples
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) >>> x masked_array( data=[[1, --, 3], [--, 5, --], [7, --, 9]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999) >>> x.compress([1, 0, 1]) masked_array(data=[1, 3], mask=[False, False], fill_value=999999)
>>> x.compress([1, 0, 1], axis=1) masked_array( data=[[1, 3], [--, --], [7, 9]], mask=[[False, False], [ True, True], [False, False]], fill_value=999999)
Parameters | |
condition:var | Boolean 1-d array selecting which entries to return. If len(condition) is less than the size of a along the axis, then output is truncated to length of condition array. |
axis:{None, int}, optional | Axis along which the operation must be performed. |
out:{None, ndarray}, optional | Alternative output array in which to place the result. It must have the same shape as the expected output but the type will be cast if necessary. |
Returns | |
MaskedArray | result - A ~ma.MaskedArray object. |
Return all the non-masked data as a 1-D array.
Notes
The result is not a MaskedArray!
Examples
>>> x = np.ma.array(np.arange(5), mask=[0]*2 + [1]*3) >>> x.compressed() array([0, 1]) >>> type(x.compressed()) <class 'numpy.ndarray'>
Returns | |
ndarray | data - A new ndarray holding the non-masked data is returned. |
Count the non-masked elements of the array along the given axis.
See Also
ma.count_masked
- Count masked elements in array or along a given axis.
Examples
>>> import numpy.ma as ma >>> a = ma.arange(6).reshape((2, 3)) >>> a[1, :] = ma.masked >>> a masked_array( data=[[0, 1, 2], [--, --, --]], mask=[[False, False, False], [ True, True, True]], fill_value=999999) >>> a.count() 3
When the axis
keyword is specified an array of appropriate size is
returned.
>>> a.count(axis=0) array([1, 1, 1]) >>> a.count(axis=1) array([3, 0])
Parameters | |
axis:None or int or tuple of ints , optional | Axis or axes along which the count is performed.
The default, None, performs the count over all
the dimensions of the input array.
New in version 1.10.0.
If this is a tuple of ints, the count is performed on multiple axes, instead of a single axis or all the axes as before. |
keepdims:bool , optional | If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array. |
Returns | |
ndarray or scalar | result - An array with the same shape as the input array, with the specified
axis removed. If the array is a 0-d array, or if axis is None, a
scalar is returned. |
Return the cumulative product of the array elements over the given axis.
Masked values are set to 1 internally during the computation. However, their position is saved, and the result will be masked at the same locations.
Refer to numpy.cumprod
for full documentation.
Notes
The mask is lost if out
is not a valid MaskedArray !
Arithmetic is modular when using integer types, and no error is raised on overflow.
See Also
numpy.ndarray.cumprod
- corresponding function for ndarrays
numpy.cumprod
- equivalent function
Return the cumulative sum of the array elements over the given axis.
Masked values are set to 0 internally during the computation. However, their position is saved, and the result will be masked at the same locations.
Refer to numpy.cumsum
for full documentation.
Notes
The mask is lost if out
is not a valid ma.MaskedArray
!
Arithmetic is modular when using integer types, and no error is raised on overflow.
See Also
numpy.ndarray.cumsum
- corresponding function for ndarrays
numpy.cumsum
- equivalent function
Examples
>>> marr = np.ma.array(np.arange(10), mask=[0,0,0,1,1,1,0,0,0,0]) >>> marr.cumsum() masked_array(data=[0, 1, 3, --, --, --, 9, 16, 24, 33], mask=[False, False, False, True, True, True, False, False, False, False], fill_value=999999)
a.dot(b, out=None)
Masked dot product of two arrays. Note that out
and strict
are
located in different positions than in ma.dot
. In order to
maintain compatibility with the functional version, it is
recommended that the optional arguments be treated as keyword only.
At some point that may be mandatory.
See Also
numpy.ma.dot
- equivalent function
Parameters | |
b:masked_array_like | Inputs array. |
out:masked_array , optional | Output argument. This must have the exact kind that would be
returned if it was not used. In particular, it must have the
right type, must be C-contiguous, and its dtype must be the
dtype that would be returned for ma.dot(a,b) . This is a
performance feature. Therefore, if these conditions are not
met, an exception is raised, instead of attempting to be
flexible. |
strict:bool , optional | Whether masked data are propagated (True) or set to 0 (False) for the computation. Default is False. Propagating the mask means that if a masked value appears in a row or column, the whole row or column is considered masked.
New in version 1.10.2.
|
numpy.ma.core.mvoid
Return a copy of self, with masked values filled with a given value. However, if there are no masked values to fill, self will be returned instead as an ndarray.
Notes
The result is not a MaskedArray!
Examples
>>> x = np.ma.array([1,2,3,4,5], mask=[0,0,1,0,1], fill_value=-999) >>> x.filled() array([ 1, 2, -999, 4, -999]) >>> x.filled(fill_value=1000) array([ 1, 2, 1000, 4, 1000]) >>> type(x.filled()) <class 'numpy.ndarray'>
Subclassing is preserved. This means that if, e.g., the data part of
the masked array is a recarray, filled
returns a recarray:
>>> x = np.array([(-1, 2), (-3, 4)], dtype='i8,i8').view(np.recarray) >>> m = np.ma.array(x, mask=[(True, False), (False, True)]) >>> m.filled() rec.array([(999999, 2), ( -3, 999999)], dtype=[('f0', '<i8'), ('f1', '<i8')])
Parameters | |
fillarray_like , optional | The value to use for invalid entries. Can be scalar or non-scalar.
If non-scalar, the resulting ndarray must be broadcastable over
input array. Default is None, in which case, the fill_value
attribute of the array is used instead. |
Returns | |
ndarray | filled_array - A copy of self with invalid entries replaced by fill_value (be it the function argument or the attribute of self), or self itself as an ndarray if there are no invalid entries to be replaced. |
Force the mask to hard, preventing unmasking by assignment.
Whether the mask of a masked array is hard or soft is determined by
its ~ma.MaskedArray.hardmask
property. harden_mask
sets
~ma.MaskedArray.hardmask
to True (and returns the modified
self).
Return the addresses of the data and mask areas.
Examples
>>> x = np.ma.array([1, 2, 3], mask=[0, 1, 1]) >>> x.ids() (166670640, 166659832) # may vary
If the array has no mask, the address of nomask
is returned. This address
is typically not close to the data in memory:
>>> x = np.ma.array([1, 2, 3]) >>> x.ids() (166691080, 3083169284) # may vary
Parameters | |
Return a boolean indicating whether the data is contiguous.
Examples
>>> x = np.ma.array([1, 2, 3]) >>> x.iscontiguous() True
iscontiguous
returns one of the flags of the masked array:
>>> x.flags C_CONTIGUOUS : True F_CONTIGUOUS : True OWNDATA : False WRITEABLE : True ALIGNED : True WRITEBACKIFCOPY : False
Parameters | |
Return the maximum along a given axis.
See Also
ma.maximum_fill_value
- Returns the maximum filling value for a given datatype.
Examples
>>> import numpy.ma as ma >>> x = [[-1., 2.5], [4., -2.], [3., 0.]] >>> mask = [[0, 0], [1, 0], [1, 0]] >>> masked_x = ma.masked_array(x, mask) >>> masked_x masked_array( data=[[-1.0, 2.5], [--, -2.0], [--, 0.0]], mask=[[False, False], [ True, False], [ True, False]], fill_value=1e+20) >>> ma.max(masked_x) 2.5 >>> ma.max(masked_x, axis=0) masked_array(data=[-1.0, 2.5], mask=[False, False], fill_value=1e+20) >>> ma.max(masked_x, axis=1, keepdims=True) masked_array( data=[[2.5], [-2.0], [0.0]], mask=[[False], [False], [False]], fill_value=1e+20) >>> mask = [[1, 1], [1, 1], [1, 1]] >>> masked_x = ma.masked_array(x, mask) >>> ma.max(masked_x, axis=1) masked_array(data=[--, --, --], mask=[ True, True, True], fill_value=1e+20, dtype=float64)
Parameters | |
axis:None or int or tuple of ints , optional | Axis along which to operate. By default, axis is None and the flattened input is used. .. versionadded:: 1.7.0 If this is a tuple of ints, the maximum is selected over multiple axes, instead of a single axis or all the axes as before. |
out:array_like , optional | Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. |
fillscalar or None , optional | Value used to fill in the masked values. If None, use the output of maximum_fill_value(). |
keepdims:bool , optional | If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array. |
Returns | |
array_like | amax - New array holding the result. If out was specified, out is returned. |
Returns the average of the array elements along given axis.
Masked entries are ignored, and result elements which are not finite will be masked.
Refer to numpy.mean
for full documentation.
See Also
numpy.ndarray.mean
- corresponding function for ndarrays
numpy.mean
- Equivalent function
numpy.ma.average
- Weighted average.
Examples
>>> a = np.ma.array([1,2,3], mask=[False, False, True]) >>> a masked_array(data=[1, 2, --], mask=[False, False, True], fill_value=999999) >>> a.mean() 1.5
Return the minimum along a given axis.
See Also
ma.minimum_fill_value
- Returns the minimum filling value for a given datatype.
Examples
>>> import numpy.ma as ma >>> x = [[1., -2., 3.], [0.2, -0.7, 0.1]] >>> mask = [[1, 1, 0], [0, 0, 1]] >>> masked_x = ma.masked_array(x, mask) >>> masked_x masked_array( data=[[--, --, 3.0], [0.2, -0.7, --]], mask=[[ True, True, False], [False, False, True]], fill_value=1e+20) >>> ma.min(masked_x) -0.7 >>> ma.min(masked_x, axis=-1) masked_array(data=[3.0, -0.7], mask=[False, False], fill_value=1e+20) >>> ma.min(masked_x, axis=0, keepdims=True) masked_array(data=[[0.2, -0.7, 3.0]], mask=[[False, False, False]], fill_value=1e+20) >>> mask = [[1, 1, 1,], [1, 1, 1]] >>> masked_x = ma.masked_array(x, mask) >>> ma.min(masked_x, axis=0) masked_array(data=[--, --, --], mask=[ True, True, True], fill_value=1e+20, dtype=float64)
Parameters | |
axis:None or int or tuple of ints , optional | Axis along which to operate. By default, axis is None and the flattened input is used. .. versionadded:: 1.7.0 If this is a tuple of ints, the minimum is selected over multiple axes, instead of a single axis or all the axes as before. |
out:array_like , optional | Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. |
fillscalar or None , optional | Value used to fill in the masked values.
If None, use the output of minimum_fill_value . |
keepdims:bool , optional | If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array. |
Returns | |
array_like | amin - New array holding the result. If out was specified, out is returned. |
Return the indices of unmasked elements that are not zero.
Returns a tuple of arrays, one for each dimension, containing the indices of the non-zero elements in that dimension. The corresponding non-zero values can be obtained with:
a[a.nonzero()]
To group the indices by element, rather than dimension, use instead:
np.transpose(a.nonzero())
The result of this is always a 2d array, with a row for each non-zero element.
See Also
numpy.nonzero
- Function operating on ndarrays.
flatnonzero
- Return indices that are non-zero in the flattened version of the input array.
numpy.ndarray.nonzero
- Equivalent ndarray method.
count_nonzero
- Counts the number of non-zero elements in the input array.
Examples
>>> import numpy.ma as ma >>> x = ma.array(np.eye(3)) >>> x masked_array( data=[[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]], mask=False, fill_value=1e+20) >>> x.nonzero() (array([0, 1, 2]), array([0, 1, 2]))
Masked elements are ignored.
>>> x[1, 1] = ma.masked >>> x masked_array( data=[[1.0, 0.0, 0.0], [0.0, --, 0.0], [0.0, 0.0, 1.0]], mask=[[False, False, False], [False, True, False], [False, False, False]], fill_value=1e+20) >>> x.nonzero() (array([0, 2]), array([0, 2]))
Indices can also be grouped by element.
>>> np.transpose(x.nonzero()) array([[0, 0], [2, 2]])
A common use for nonzero is to find the indices of an array, where
a condition is True. Given an array a
, the condition a
> 3 is a
boolean array and since False is interpreted as 0, ma.nonzero(a > 3)
yields the indices of the a
where the condition is true.
>>> a = ma.array([[1,2,3],[4,5,6],[7,8,9]]) >>> a > 3 masked_array( data=[[False, False, False], [ True, True, True], [ True, True, True]], mask=False, fill_value=True) >>> ma.nonzero(a > 3) (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
The nonzero method of the condition array can also be called.
>>> (a > 3).nonzero() (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
Parameters | |
Returns | |
tuple | tuple_of_arrays - Indices of elements that are non-zero. |
Return the product of the array elements over the given axis.
Masked elements are set to 1 internally for computation.
Refer to numpy.prod
for full documentation.
Notes
Arithmetic is modular when using integer types, and no error is raised on overflow.
See Also
numpy.ndarray.prod
- corresponding function for ndarrays
numpy.prod
- equivalent function
Return (maximum - minimum) along the given dimension (i.e. peak-to-peak value).
Warning
ptp
preserves the data type of the array. This means the
return value for an input of signed integers with n bits
(e.g. np.int8
, np.int16
, etc) is also a signed integer
with n bits. In that case, peak-to-peak values greater than
2**(n-1)-1 will be returned as negative values. An example
with a work-around is shown below.
Examples
>>> x = np.ma.MaskedArray([[4, 9, 2, 10], ... [6, 9, 7, 12]])
>>> x.ptp(axis=1) masked_array(data=[8, 6], mask=False, fill_value=999999)
>>> x.ptp(axis=0) masked_array(data=[2, 0, 5, 2], mask=False, fill_value=999999)
>>> x.ptp() 10
This example shows that a negative value can be returned when the input is an array of signed integers.
>>> y = np.ma.MaskedArray([[1, 127], ... [0, 127], ... [-1, 127], ... [-2, 127]], dtype=np.int8) >>> y.ptp(axis=1) masked_array(data=[ 126, 127, -128, -127], mask=False, fill_value=999999, dtype=int8)
A work-around is to use the view()
method to view the result as
unsigned integers with the same bit width:
>>> y.ptp(axis=1).view(np.uint8) masked_array(data=[126, 127, 128, 129], mask=False, fill_value=999999, dtype=uint8)
Parameters | |
axis:{None, int}, optional | Axis along which to find the peaks. If None (default) the flattened array is used. |
out:{None, array_like}, optional | Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output but the type will be cast if necessary. |
fillscalar or None , optional | Value used to fill in the masked values. |
keepdims:bool , optional | If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array. |
Returns | |
ndarray. | ptp - A new array holding the result, unless out was specified, in which case a reference to out is returned. |
Set storage-indexed locations to corresponding values.
Sets self._data.flat[n] = values[n] for each n in indices.
If values
is shorter than indices
then it will repeat.
If values
has some masked values, the initial mask is updated
in consequence, else the corresponding values are unmasked.
Notes
values
can be a scalar or length 1 array.
Examples
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) >>> x masked_array( data=[[1, --, 3], [--, 5, --], [7, --, 9]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999) >>> x.put([0,4,8],[10,20,30]) >>> x masked_array( data=[[10, --, 3], [--, 20, --], [7, --, 30]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999)
>>> x.put(4,999) >>> x masked_array( data=[[10, --, 3], [--, 999, --], [7, --, 30]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999)
Parameters | |
indices:1-D array_like | Target indices, interpreted as integers. |
values:array_like | Values to place in self._data copy at target indices. |
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 a 1D version of self, as a view.
Examples
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) >>> x masked_array( data=[[1, --, 3], [--, 5, --], [7, --, 9]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999) >>> x.ravel() masked_array(data=[1, --, 3, --, 5, --, 7, --, 9], mask=[False, True, False, True, False, True, False, True, False], fill_value=999999)
Parameters | |
order:{'C', 'F', 'A', 'K'}, optional | The elements of a are read using this index order. 'C' means to
index the elements in C-like order, with the last axis index
changing fastest, back to the first axis index changing slowest.
'F' means to index the elements in Fortran-like index order, with
the first index changing fastest, and the last index changing
slowest. Note that the 'C' and 'F' options take no account of the
memory layout of the underlying array, and only refer to the order
of axis indexing. 'A' means to read the elements in Fortran-like
index order if m is Fortran contiguous in memory, C-like order
otherwise. 'K' means to read the elements in the order they occur
in memory, except for reversing the data when strides are negative.
By default, 'C' index order is used. |
Returns | |
MaskedArray | Output view is of shape (self.size,) (or (np.ma.product(self.shape),)). |
Give a new shape to the array without changing its data.
Returns a masked array containing the same data, but with a new shape. The result is a view on the original array; if this is not possible, a ValueError is raised.
See Also
reshape
- Equivalent function in the masked array module.
numpy.ndarray.reshape
- Equivalent method on ndarray object.
numpy.reshape
- Equivalent function in the NumPy module.
Notes
The reshaping operation cannot guarantee that a copy will not be made, to modify the shape in place, use a.shape = s
Examples
>>> x = np.ma.array([[1,2],[3,4]], mask=[1,0,0,1]) >>> x masked_array( data=[[--, 2], [3, --]], mask=[[ True, False], [False, True]], fill_value=999999) >>> x = x.reshape((4,1)) >>> x masked_array( data=[[--], [2], [3], [--]], mask=[[ True], [False], [False], [ True]], fill_value=999999)
Parameters | |
*s | Undocumented |
**kwargs | Undocumented |
shape:int or tuple of ints | The new shape should be compatible with the original shape. If an integer is supplied, then the result will be a 1-D array of that length. |
order:{'C', 'F'}, optional | Determines whether the array data should be viewed as in C (row-major) or FORTRAN (column-major) order. |
Returns | |
array | reshaped_array - A new view on the array. |
Warning
This method does nothing, except raise a ValueError exception. A
masked array does not own its data and therefore cannot safely be
resized in place. Use the numpy.ma.resize
function instead.
This method is difficult to implement safely and may be deprecated in future releases of NumPy.
Return each element rounded to the given number of decimals.
Refer to numpy.around
for full documentation.
See Also
numpy.ndarray.round
- corresponding function for ndarrays
numpy.around
- equivalent function
Reduce a mask to nomask when possible.
Examples
>>> x = np.ma.array([[1,2 ], [3, 4]], mask=[0]*4) >>> x.mask array([[False, False], [False, False]]) >>> x.shrink_mask() masked_array( data=[[1, 2], [3, 4]], mask=False, fill_value=999999) >>> x.mask False
Parameters | |
Returns | |
None | Undocumented |
Force the mask to soft (default), allowing unmasking by assignment.
Whether the mask of a masked array is hard or soft is determined by
its ~ma.MaskedArray.hardmask
property. soften_mask
sets
~ma.MaskedArray.hardmask
to False (and returns the modified
self).
Sort the array, in-place
See Also
numpy.ndarray.sort
- Method to sort an array in-place.
argsort
- Indirect sort.
lexsort
- Indirect stable sort on multiple keys.
searchsorted
- Find elements in a sorted array.
Notes
See sort for notes on the different sorting algorithms.
Examples
>>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0]) >>> # Default >>> a.sort() >>> a masked_array(data=[1, 3, 5, --, --], mask=[False, False, False, True, True], fill_value=999999)
>>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0]) >>> # Put missing values in the front >>> a.sort(endwith=False) >>> a masked_array(data=[--, --, 1, 3, 5], mask=[ True, True, False, False, False], fill_value=999999)
>>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0]) >>> # fill_value takes over endwith >>> a.sort(endwith=False, fill_value=3) >>> a masked_array(data=[1, --, --, 3, 5], mask=[False, True, True, False, False], fill_value=999999)
Parameters | |
axis:int , optional | Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis. |
kind:{'quicksort', 'mergesort', 'heapsort', 'stable'}, optional | The sorting algorithm used. |
order:list , optional | When a is a structured array, this argument specifies which fields
to compare first, second, and so on. This list does not need to
include all of the fields. |
endwith:{True, False}, optional | Whether missing values (if any) should be treated as the largest values (True) or the smallest values (False) When the array contains unmasked values sorting at the same extremes of the datatype, the ordering of these values and the masked values is undefined. |
fillscalar or None , optional | Value used internally for the masked values. If fill_value is not None, it supersedes endwith. |
a:array_like | Array to be sorted. |
Returns | |
ndarray | sorted_array - Array of the same type and shape as a . |
Returns the standard deviation of the array elements along given axis.
Masked entries are ignored.
Refer to numpy.std
for full documentation.
See Also
numpy.ndarray.std
- corresponding function for ndarrays
numpy.std
- Equivalent function
Return the sum of the array elements over the given axis.
Masked elements are set to 0 internally.
Refer to numpy.sum
for full documentation.
See Also
numpy.ndarray.sum
- corresponding function for ndarrays
numpy.sum
- equivalent function
Examples
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) >>> x masked_array( data=[[1, --, 3], [--, 5, --], [7, --, 9]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999) >>> x.sum() 25 >>> x.sum(axis=1) masked_array(data=[4, 5, 16], mask=[False, False, False], fill_value=999999) >>> x.sum(axis=0) masked_array(data=[8, 5, 12], mask=[False, False, False], fill_value=999999) >>> print(type(x.sum(axis=0, dtype=np.int64)[0])) <class 'numpy.int64'>
Return the array data as a string containing the raw bytes in the array.
The array is filled with a fill value before the string conversion.
Notes
As for ndarray.tobytes
, information about the shape, dtype, etc.,
but also about fill_value
, will be lost.
Examples
>>> x = np.ma.array(np.array([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]]) >>> x.tobytes() b'\x01\x00\x00\x00\x00\x00\x00\x00?B\x0f\x00\x00\x00\x00\x00?B\x0f\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00'
Parameters | |
fillscalar , optional | Value used to fill in the masked values. Default is None, in which
case MaskedArray.fill_value is used. |
order:{'C', 'F', 'A'}, optional | Order of the data item in the copy. Default is 'C'.
|
Save a masked array to a file in binary format.
Warning
This function is not implemented yet.
Raises | |
NotImplementedError | When tofile is called. |
Transforms a masked array into a flexible-type array.
The flexible type array that is returned will have two fields:
- the _data field stores the _data part of the array.
- the _mask field stores the _mask part of the array.
Notes
A side-effect of transforming a masked array into a flexible ndarray
is
that meta information (fill_value, ...) will be lost.
Examples
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) >>> x masked_array( data=[[1, --, 3], [--, 5, --], [7, --, 9]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999) >>> x.toflex() array([[(1, False), (2, True), (3, False)], [(4, True), (5, False), (6, True)], [(7, False), (8, True), (9, False)]], dtype=[('_data', '<i8'), ('_mask', '?')])
Parameters | |
Returns | |
ndarray | record - A new flexible-type ndarray with two fields: the first element
containing a value, the second element containing the corresponding
mask boolean. The returned record shape matches self.shape. |
numpy.ma.core.mvoid
Return the data portion of the masked array as a hierarchical Python list.
Data items are converted to the nearest compatible Python type.
Masked values are converted to fill_value
. If fill_value
is None,
the corresponding entries in the output list will be None.
Examples
>>> x = np.ma.array([[1,2,3], [4,5,6], [7,8,9]], mask=[0] + [1,0]*4) >>> x.tolist() [[1, None, 3], [None, 5, None], [7, None, 9]] >>> x.tolist(-999) [[1, -999, 3], [-999, 5, -999], [7, -999, 9]]
Parameters | |
fillscalar , optional | The value to use for invalid entries. Default is None. |
Returns | |
list | result - The Python list representation of the masked array. |
Copy the mask and set the sharedmask
flag to False.
Whether the mask is shared between masked arrays can be seen from
the sharedmask
property. unshare_mask
ensures the mask is not
shared. A copy of the mask is only made if it was shared.
See Also
Returns the variance of the array elements along given axis.
Masked entries are ignored, and result elements which are not finite will be masked.
Refer to numpy.var
for full documentation.
See Also
numpy.ndarray.var
- corresponding function for ndarrays
numpy.var
- Equivalent function
Return a view of the MaskedArray data.
See Also
numpy.ndarray.view
- Equivalent method on ndarray object.
Notes
a.view() is used two different ways:
a.view(some_dtype) or a.view(dtype=some_dtype) constructs a view of the array's memory with a different data-type. This can cause a reinterpretation of the bytes of memory.
a.view(ndarray_subclass) or a.view(type=ndarray_subclass) just
returns an instance of ndarray_subclass
that looks at the same array
(same shape, dtype, etc.) This does not cause a reinterpretation of the
memory.
If fill_value
is not specified, but dtype
is specified (and is not
an ndarray sub-class), the fill_value
of the MaskedArray will be
reset. If neither fill_value
nor dtype
are specified (or if
dtype
is an ndarray sub-class), then the fill value is preserved.
Finally, if fill_value
is specified, but dtype
is not, the fill
value is set to the specified value.
For a.view(some_dtype), if some_dtype has a different number of bytes per entry than the previous dtype (for example, converting a regular array to a structured array), then the behavior of the view cannot be predicted just from the superficial appearance of a (shown by print(a)). It also depends on exactly how a is stored in memory. Therefore if a is C-ordered versus fortran-ordered, versus defined as a slice or transpose, etc., the view may give different results.
Parameters | |
dtype:data-type or ndarray sub-class, optional | Data-type descriptor of the returned view, e.g., float32 or int16.
The default, None, results in the view having the same data-type
as a . As with ndarray.view, dtype can also be specified as
an ndarray sub-class, which then specifies the type of the
returned object (this is equivalent to setting the type
parameter). |
type:Python type, optional | Type of the returned view, either ndarray or a subclass. The default None results in type preservation. |
fillscalar , optional | The value to use for invalid entries (None by default).
If None, then this argument is inferred from the passed dtype , or
in its absence the original array, as discussed in the notes below. |
The filling value of the masked array is a scalar. When setting, None will set to a default based on the data type.
Examples
>>> for dt in [np.int32, np.int64, np.float64, np.complex128]: ... np.ma.array([0, 1], dtype=dt).get_fill_value() ... 999999 999999 1e+20 (1e+20+0j)
>>> x = np.ma.array([0, 1.], fill_value=-np.inf) >>> x.fill_value -inf >>> x.fill_value = np.pi >>> x.fill_value 3.1415926535897931 # may vary
Reset to default:
>>> x.fill_value = None >>> x.fill_value 1e+20
Specifies whether values can be unmasked through assignments.
By default, assigning definite values to masked array entries will
unmask them. When hardmask
is True, the mask will not change
through assignments.
Examples
>>> x = np.arange(10) >>> m = np.ma.masked_array(x, x>5) >>> assert not m.hardmask
Since m
has a soft mask, assigning an element value unmasks that
element:
>>> m[8] = 42 >>> m masked_array(data=[0, 1, 2, 3, 4, 5, --, --, 42, --], mask=[False, False, False, False, False, False, True, True, False, True], fill_value=999999)
After hardening, the mask is not affected by assignments:
>>> hardened = np.ma.harden_mask(m) >>> assert m.hardmask and hardened is m >>> m[:] = 23 >>> m masked_array(data=[23, 23, 23, 23, 23, 23, --, --, 23, --], mask=[False, False, False, False, False, False, True, True, False, True], fill_value=999999)
The imaginary part of the masked array.
This property is a view on the imaginary part of this MaskedArray
.
See Also
Examples
>>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False]) >>> x.imag masked_array(data=[1.0, --, 1.6], mask=[False, True, False], fill_value=1e+20)
The real part of the masked array.
This property is a view on the real part of this MaskedArray
.
See Also
Examples
>>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False]) >>> x.real masked_array(data=[1.0, --, 3.45], mask=[False, True, False], fill_value=1e+20)
Get or set the mask of the array if it has no named fields. For structured arrays, returns a ndarray of booleans where entries are True if all the fields are masked, False otherwise:
>>> x = np.ma.array([(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)], ... mask=[(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)], ... dtype=[('a', int), ('b', int)]) >>> x.recordmask array([False, False, True, False, False])
Compare self with other using operator.eq or operator.ne.
When either of the elements is masked, the result is masked as well, but the underlying boolean data are still set, with self and other considered equal if both are masked, and unequal otherwise.
For structured arrays, all fields are combined, with masked values ignored. The result is masked if all fields were masked, with self and other considered equal only if both were fully masked.
Returns the underlying data, as a view of the masked array.
If the underlying data is a subclass of numpy.ndarray
, it is
returned as such.
>>> x = np.ma.array(np.matrix([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]]) >>> x.data matrix([[1, 2], [3, 4]])
The type of the data can be accessed through the baseclass
attribute.