For my unittest, I want to check if two arrays are identical. Reduced example:
a = np.array([1, 2, np.NaN])
b = np.array([1, 2, np.NaN])
if np.all(a==b):
print 'arrays are equal'
This does not work because nan != nan
.
What is the best way to proceed?
For versions of numpy prior to 1.19, this is probably the best approach in situations that don't specifically involve unit tests:
>>> ((a == b) | (numpy.isnan(a) & numpy.isnan(b))).all()
True
However, modern versions provide the array_equal
function with a new keyword argument, equal_nan
, which fits the bill exactly.
This was first pointed out by flyingdutchman; see his answer below for details.