TExcelTAD
Home › NumPy › NaN and Masked Arrays

NaN and Masked Arrays

Real data has gaps: a sensor drops out, a survey question is skipped, a value is clearly wrong. NumPy offers two ways to represent missing values:

  1. NaN ("Not a Number"), a special floating-point value, np.nan.
  2. Masked arrays (numpy.ma), which pair the data with a boolean mask of invalid entries.

NaN basics

NaN is part of the floating-point standard. It spreads: any arithmetic involving NaN gives NaN, and NaN is not equal to anything, not even itself.

python · try it yourself
import numpy as np

temps = np.array([21.5, np.nan, 23.0, 22.1, np.nan, 20.8])
print(temps)
print("mean:", temps.mean())               # one NaN poisons the result
print(np.nan == np.nan)                    # False!
print("missing:", np.isnan(temps))
print("count missing:", np.isnan(temps).sum())
[21.5  nan 23.  22.1  nan 20.8]
mean: nan
False
missing: [False  True False False  True False]
count missing: 2

Because x == np.nan is always False, always test with np.isnan(x).

Note: NaN only exists for floats. An integer array can't hold NaN; assigning np.nan to one raises an error. Convert to float first, or use a masked array.

NaN-aware functions

For most aggregations there is a nan-prefixed version that simply skips NaNs:

Normal NaN-aware
np.sum np.nansum
np.mean np.nanmean
np.std, np.var np.nanstd, np.nanvar
np.min, np.max np.nanmin, np.nanmax
np.argmin, np.argmax np.nanargmin, np.nanargmax
np.median, np.percentile np.nanmedian, np.nanpercentile
python · try it yourself
import numpy as np

temps = np.array([[21.5, np.nan, 23.0],
                  [22.1, np.nan, 20.8],
                  [19.9, 24.2, np.nan]])
print("overall mean:", np.nanmean(temps).round(3))
print("mean per row:", np.nanmean(temps, axis=1).round(3))
print("max per column:", np.nanmax(temps, axis=0))
print("valid per column:", (~np.isnan(temps)).sum(axis=0))
overall mean: 21.917
mean per row: [22.25 21.45 22.05]
max per column: [22.1 24.2 23. ]
valid per column: [3 1 2]

Cleaning: drop or fill

The two standard strategies are to remove missing values or replace them:

python · try it yourself
import numpy as np

steps = np.array([8200.0, np.nan, 10400.0, 7600.0, np.nan, 9100.0])

clean = steps[~np.isnan(steps)]                       # drop
print("dropped:", clean)

filled = np.where(np.isnan(steps), np.nanmean(steps), steps)   # fill with the mean
print("filled: ", filled)

print("zeros:  ", np.nan_to_num(steps, nan=0.0))       # fill with a constant
dropped: [ 8200. 10400.  7600.  9100.]
filled:  [ 8200.  8825. 10400.  7600.  8825.  9100.]
zeros:   [ 8200.     0. 10400.  7600.     0.  9100.]

For time series, a common fill is linear interpolation between the neighbours. np.interp does it in one line:

python · try it yourself
import numpy as np

level = np.array([1.0, 1.4, np.nan, np.nan, 2.6, 2.9])
idx = np.arange(len(level))
ok = ~np.isnan(level)
level[~ok] = np.interp(idx[~ok], idx[ok], level[ok])
print(level)
[1.  1.4 1.8 2.2 2.6 2.9]

Masked arrays

A masked array keeps the original values but marks some of them as invalid. Every operation then ignores the masked entries. It works for any dtype, including integers, and is handy for sentinel values like -999 that some file formats use for "missing":

python · try it yourself
import numpy as np
import numpy.ma as ma

rain_mm = np.array([3, -999, 0, 12, -999, 7])        # -999 = sensor offline
rain = ma.masked_equal(rain_mm, -999)
print(rain)
print("mean:", rain.mean(), " total:", rain.sum(), " valid:", rain.count())
print("mask:", rain.mask)
print("filled:", rain.filled(0))
[3 -- 0 12 -- 7]
mean: 5.5  total: 22  valid: 4
mask: [False  True False False  True False]
filled: [ 3  0  0 12  0  7]

-- marks masked positions in the printout. filled(value) gives back a normal array with the masked entries replaced.

You can also build the mask from any condition, for example to exclude implausible readings:

python · try it yourself
import numpy as np
import numpy.ma as ma

heart_rate = np.array([72, 75, 250, 68, 0, 80])       # 250 and 0 are glitches
hr = ma.masked_outside(heart_rate, 30, 220)
print(hr)
print("average:", hr.mean())
print("raw average would be:", heart_rate.mean())
[72 75 -- 68 -- 80]
average: 73.75
raw average would be: 90.83333333333333
NaN Masked array
Works with floats only any dtype
Keeps original values no (replaced by NaN) yes
Functions np.nan* versions the normal ones, via numpy.ma
Common in pandas, everyday analysis scientific data, sentinel values

Test yourself

What does np.nan == np.nan return?

  1. True
  2. False
  3. nan
  4. An error

Which function averages an array while ignoring NaN values?

  1. np.mean
  2. np.nanmean
  3. np.average
  4. np.meannan

Why might you prefer a masked array over NaN?

  1. It is always faster
  2. It works for integer arrays and keeps the original values
  3. NaN cannot be printed
  4. Masked arrays use less memory than anything else