Skip to content

Backport PR #31910 on branch 1.0.x (BUG: Handle NA in assert_numpy_array_equal) #31947

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions pandas/_libs/lib.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,8 @@ def array_equivalent_object(left: object[:], right: object[:]) -> bool:
if PyArray_Check(x) and PyArray_Check(y):
if not array_equivalent_object(x, y):
return False
elif (x is C_NA) ^ (y is C_NA):
return False
elif not (PyObject_RichCompareBool(x, y, Py_EQ) or
(x is None or is_nan(x)) and (y is None or is_nan(y))):
return False
Expand Down
36 changes: 36 additions & 0 deletions pandas/tests/util/test_assert_numpy_array_equal.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import numpy as np
import pytest

import pandas as pd
from pandas import Timestamp
import pandas._testing as tm

Expand Down Expand Up @@ -175,3 +176,38 @@ def test_numpy_array_equal_copy_flag(other_type, check_same):
tm.assert_numpy_array_equal(a, other, check_same=check_same)
else:
tm.assert_numpy_array_equal(a, other, check_same=check_same)


def test_numpy_array_equal_contains_na():
# https://github.com/pandas-dev/pandas/issues/31881
a = np.array([True, False])
b = np.array([True, pd.NA], dtype=object)

msg = """numpy array are different

numpy array values are different \\(50.0 %\\)
\\[left\\]: \\[True, False\\]
\\[right\\]: \\[True, <NA>\\]"""

with pytest.raises(AssertionError, match=msg):
tm.assert_numpy_array_equal(a, b)


def test_numpy_array_equal_identical_na(nulls_fixture):
a = np.array([nulls_fixture], dtype=object)

tm.assert_numpy_array_equal(a, a)


def test_numpy_array_equal_different_na():
a = np.array([np.nan], dtype=object)
b = np.array([pd.NA], dtype=object)

msg = """numpy array are different

numpy array values are different \\(100.0 %\\)
\\[left\\]: \\[nan\\]
\\[right\\]: \\[<NA>\\]"""

with pytest.raises(AssertionError, match=msg):
tm.assert_numpy_array_equal(a, b)