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?
To check for NaN values in a Numpy array you can use the np. isnan() method. This outputs a boolean mask of the size that of the original array. The output array has true for the indices which are NaNs in the original array and false for the rest.
Method 1: We generally use the == operator to compare two NumPy arrays to generate a new array object. Call ndarray. all() with the new array object as ndarray to return True if the two NumPy arrays are equivalent.
In Python, NumPy with the latest version where nan is a value only for floating arrays only which stands for not a number and is a numeric data type which is used to represent an undefined value. In Python, NumPy defines NaN as a constant value.
To compare two arrays and return the element-wise minimum, use the numpy. fmin() method in Python Numpy. Return value is either True or False. Compare two arrays and returns a new array containing the element-wise maxima.
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.
Alternatively you can use numpy.testing.assert_equal
or numpy.testing.assert_array_equal
with a try/except
:
In : import numpy as np In : def nan_equal(a,b): ...: try: ...: np.testing.assert_equal(a,b) ...: except AssertionError: ...: return False ...: return True In : a=np.array([1, 2, np.NaN]) In : b=np.array([1, 2, np.NaN]) In : nan_equal(a,b) Out: True In : a=np.array([1, 2, np.NaN]) In : b=np.array([3, 2, np.NaN]) In : nan_equal(a,b) Out: False
Edit
Since you are using this for unittesting, bare assert
(instead of wrapping it to get True/False
) might be more natural.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With