comparing numpy arrays containing NaN

后端 未结 7 1576
情话喂你
情话喂你 2020-11-28 09:27

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):
          


        
7条回答
  •  日久生厌
    2020-11-28 10:23

    Just to complete @Luis Albert Centeno’s answer, you may rather use:

    np.allclose(a, b, rtol=0, atol=0, equal_nan=True)
    

    rtol and atol control the tolerance of the equality test. In short, allclose() returns:

    all(abs(a - b) <= atol + rtol * abs(b))
    

    By default they are not set to 0, so the function could return True if your numbers are close but not exactly equal.


    PS: "I want to check if two arrays are identical " >> Actually, you are looking for equality rather than identity. They are not the same in Python and I think it’s better for everyone to understand the difference so as to share the same lexicon. (https://www.blog.pythonlibrary.org/2017/02/28/python-101-equality-vs-identity/)

    You’d test identity via keyword is:

    a is b
    

提交回复
热议问题