Skip to main content
`Ctrl`+`K`

# The `numpy.ma` module

## Rationale

Masked arrays are arrays that may have missing or invalid entries. The `numpy.ma` module provides a nearly work-alike replacement for numpy that supports data arrays with masks.

## What is a masked array?

In many circumstances, datasets can be incomplete or tainted by the presence of invalid data. For example, a sensor may have failed to record a data point, or recorded an invalid value. The `numpy.ma` module provides a convenient way to address this issue, by introducing masked arrays.

A masked array is the combination of a standard `numpy.ndarray` and a mask. A mask is either `nomask`, indicating that no value of the associated array is invalid, or an array of booleans that determines for each element of the associated array whether the value is valid or not. When an element of the mask is `False`, the corresponding element of the associated array is valid and is said to be unmasked. When an element of the mask is `True`, the corresponding element of the associated array is said to be masked (invalid).

The package ensures that masked entries are not used in computations.

## The `numpy.ma` module

The main feature of the `numpy.ma` module is the `MaskedArray` class, which is a subclass of `numpy.ndarray`. The class, its attributes and methods are described in more details in the MaskedArray class section.

For a complete discussion of creation methods for masked arrays please see section Constructing masked arrays.

# Using numpy.ma

## Constructing masked arrays

There are several ways to construct a masked array.

- A first possibility is to directly invoke the `MaskedArray` class.

- A second possibility is to use the two masked array constructors, `array` and `masked_array`.

  `array`(data[, dtype, copy, order, mask, ...]) | An array class with possibly masked values.
  `masked_array` |

- A third option is to take the view of an existing array. In that case, the mask of the view is set to `nomask` if the array has no named fields, or an array of boolean with the same structure as the array otherwise.

- Yet another possibility is to use any of the following functions:

  `asarray`(a[, dtype, order]) | Convert the input to a masked array of the given data-type.
  `asanyarray`(a[, dtype, order]) | Convert the input to a masked array, conserving subclasses.
  `fix_invalid`(a[, mask, copy, fill_value]) | Return input with invalid data masked and replaced by a fill value.
  `masked_equal`(x, value[, copy]) | Mask an array where equal to a given value.
  `masked_greater`(x, value[, copy]) | Mask an array where greater than a given value.
  `masked_greater_equal`(x, value[, copy]) | Mask an array where greater than or equal to a given value.
  `masked_inside`(x, v1, v2[, copy]) | Mask an array inside a given interval.
  `masked_invalid`(a[, copy]) | Mask an array where invalid values occur (NaNs or infs).
  `masked_less`(x, value[, copy]) | Mask an array where less than a given value.
  `masked_less_equal`(x, value[, copy]) | Mask an array where less than or equal to a given value.
  `masked_not_equal`(x, value[, copy]) | Mask an array where not equal to a given value.
  `masked_object`(x, value[, copy, shrink]) | Mask the array x where the data are exactly equal to value.
  `masked_outside`(x, v1, v2[, copy]) | Mask an array outside a given interval.
  `masked_values`(x, value[, rtol, atol, copy, ...]) | Mask using floating point equality.
  `masked_where`(condition, a[, copy]) | Mask an array where a condition is met.

## Accessing the data

The underlying data of a masked array can be accessed in several ways:

- through the `data` attribute. The output is a view of the array as a `numpy.ndarray` or one of its subclasses, depending on the type of the underlying data at the masked array creation.

- through the `__array__` method. The output is then a `numpy.ndarray`.

- by directly taking a view of the masked array as a `numpy.ndarray` or one of its subclass (which is actually what using the `data` attribute does).

- by using the `getdata` function.

None of these methods is completely satisfactory if some entries have been marked as invalid. As a general rule, where a representation of the array is required without any masked entries, it is recommended to fill the array with the `filled` method.

## Accessing the mask

The mask of a masked array is accessible through its `mask` attribute. We must keep in mind that a `True` entry in the mask indicates an invalid data.

Another possibility is to use the `getmask` and `getmaskarray` functions. `getmask(x)` outputs the mask of `x` if `x` is a masked array, and the special value `nomask` otherwise. `getmaskarray(x)` outputs the mask of `x` if `x` is a masked array. If `x` has no invalid entry or is not a masked array, the function outputs a boolean array of `False` with as many elements as `x`.

## Accessing only the valid entries

To retrieve only the valid entries, we can use the inverse of the mask as an index. The inverse of the mask can be calculated with the `numpy.logical_not` function or simply with the `~` operator:

## Modifying the mask

### Masking an entry

The recommended way to mark one or several specific entries of a masked array as invalid is to assign the special value `masked` to them:

A second possibility is to modify the `mask` directly, but this usage is discouraged.

Note

When creating a new masked array with a simple, non-structured datatype, the mask is initially set to the special value `nomask`, that corresponds roughly to the boolean `False`. Trying to set an element of `nomask` will fail with a `TypeError` exception, as a boolean does not support item assignment.

All the entries of an array can be masked at once by assigning `True` to the mask:

### Unmasking an entry

To unmask one or several specific entries, we can just assign one or several new valid values to them:

Note

Unmasking an entry by direct assignment will silently fail if the masked array has a hard mask, as shown by the `hardmask` attribute. This feature was introduced to prevent overwriting the mask. To force the unmasking of an entry where the array has a hard mask, the mask must first to be softened using the `soften_mask` method before the allocation. It can be re-hardened with `harden_mask` as follows:

To unmask all masked entries of a masked array (provided the mask isn’t a hard mask), the simplest solution is to assign the constant `nomask` to the mask:

## Indexing and slicing

As a `MaskedArray` is a subclass of `numpy.ndarray`, it inherits its mechanisms for indexing and slicing.

When accessing a single entry of a masked array with no named fields, the output is either a scalar (if the corresponding entry of the mask is `False`) or the special value `masked` (if the corresponding entry of the mask is `True`):

If the masked array has named fields, accessing a single entry returns a `numpy.void` object if none of the fields are masked, or a 0d masked array with the same dtype as the initial array if at least one of the fields is masked.

When accessing a slice, the output is a masked array whose `data` attribute is a view of the original data, and whose mask is either `nomask` (if there was no invalid entries in the original array) or a view of the corresponding slice of the original mask. The view is required to ensure propagation of any modification of the mask to the original.

Accessing a field of a masked array with structured datatype returns a `MaskedArray`.

## Operations on masked arrays

Arithmetic and comparison operations are supported by masked arrays. As much as possible, invalid entries of a masked array are not processed, meaning that the corresponding `data` entries should be the same before and after the operation.

Warning

We need to stress that this behavior may not be systematic, that masked data may be affected by the operation in some cases and therefore users should not rely on this data remaining unchanged.

The `numpy.ma` module comes with a specific implementation of most ufuncs. Unary and binary functions that have a validity domain (such as `log` or `divide`) return the `masked` constant whenever the input is masked or falls outside the validity domain:

Masked arrays also support standard numpy ufuncs. The output is then a masked array. The result of a unary ufunc is masked wherever the input is masked. The result of a binary ufunc is masked wherever any of the input is masked. If the ufunc also returns the optional context output (a 3-element tuple containing the name of the ufunc, its arguments and its domain), the context is processed and entries of the output masked array are masked wherever the corresponding input fall outside the validity domain:

# Examples

## Data with a given value representing missing data

Let’s consider a list of elements, `x`, where values of -9999. represent missing data. We wish to compute the average value of the data and the vector of anomalies (deviations from the average):

## Filling in the missing data

Suppose now that we wish to print that same data, but with the missing values replaced by the average value.

## Numerical operations

Numerical operations can be easily performed without worrying about missing values, dividing by zero, square roots of negative numbers, etc.:

Four values of the output are invalid: the first one comes from taking the square root of a negative number, the second from the division by zero, and the last two where the inputs were masked.

## Ignoring extreme values

Let’s consider an array `d` of floats between 0 and 1. We wish to compute the average of the values of `d` while ignoring any data outside the range `[0.2, 0.9]`: