Masked arrays
Masked arrays let you hide bad or missing values so calculations skip over them.
In this page:
Syntax
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
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
- Reading the mask backwards
- Forgetting normal functions do not respect masks
- 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: