← Back to NumPy Course | Chapter 12: Advanced Topics | Lesson 5 of 7

Masked arrays

Masked arrays let you hide bad or missing values so calculations skip over them.

In this page:

  1. Masked arrays
Syntax
python
masked = np.ma.masked_array(data, mask=boolean_mask)
masked.mean()

Masked arrays

np.ma.masked_array pairs data with a boolean mask; masked entries are ignored by functions such as mean and sum. Helpers like masked_where and masked_invalid build masks from conditions. Use .filled() to replace masked values.

Note: A True in the mask means the value is hidden, the opposite of a boolean index.

Example: Masked arrays

python
import numpy as np

data = np.array([10, -999, 30, -999, 50])
m = np.ma.masked_where(data == -999, data)
print(m)
print("mean:", m.mean())
print(m.filled(0))

# Output:
# [10 -- 30 -- 50]
# mean: 30.0
# [10  0 30  0 50]
Related Topics
Common Mistakes
  1. Reading the mask backwards
  2. Forgetting normal functions do not respect masks
  3. Losing the mask by converting to a plain array
Chapter Summary
  • Masked entries are ignored
  • True in the mask hides a value
  • masked_where builds masks
  • filled replaces masked values
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.