Integer Arrays
Mask your arrays using np.isfinite
and compare with np.array_equal
:
def array_nan_equal(a, b):
m = np.isfinite(a) & np.isfinite(b)
return np.array_equal(a[m], b[m])
assert array_nan_equal(
np.array([1, np.nan, 3, np.nan]), np.array([1, 2, 3, 4])
)
assert not array_nan_equal(
np.array([1, 4, 3, np.nan]), np.array([1, 2, 3, 4])
)
Note that if you want to account for +/-inf
, you can follow the cue in @Paul Panzer's answer and use m = ~(np.isnan(a) & np.isnan(b))
instead of np.isfinite
.
Floating Point Arrays
For floats, you'd need to compare within a tolerance, so substitute np.array_equal
with a call to np.allclose
:
def array_nan_close(a, b):
m = np.isfinite(a) & np.isfinite(b)
return np.allclose(a[m], b[m])
assert array_nan_close(
np.array([1.3, np.nan, 3.4, np.nan]), np.array([1.3000001, 2, 3.4, 4])
)
assert not array_nan_close(
np.array([1.1, 4.0, 3.5, np.nan]), np.array([1, 2, 3, 4])
)