Skip to content

BUG: Fix assert_frame_equal with check_dtype=False for pd.NA dtype differences (GH#61473) #61748

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
14 changes: 14 additions & 0 deletions pandas/_testing/asserters.py
Original file line number Diff line number Diff line change
Expand Up @@ -1316,6 +1316,20 @@ def assert_frame_equal(
lcol = left._ixs(i, axis=1)
rcol = right._ixs(i, axis=1)

# Fix for issue #61473: Handle pd.NA values when check_dtype=False
if not check_dtype:
# Normalize both pd.NA and np.nan to the same representation for comparison
# This allows comparison between object and Int32 dtypes with pd.NA
lcol_normalized = lcol.copy()
rcol_normalized = rcol.copy()

# Replace all null values (pd.NA, np.nan) with a consistent representation
lcol_normalized = lcol_normalized.where(lcol_normalized.notna(), np.nan)
rcol_normalized = rcol_normalized.where(rcol_normalized.notna(), np.nan)

lcol = lcol_normalized
rcol = rcol_normalized

# GH #38183
# use check_index=False, because we do not want to run
# assert_index_equal for each column,
Expand Down
21 changes: 21 additions & 0 deletions pandas/tests/util/test_assert_frame_equal.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import pandas as pd
from pandas import DataFrame
import pandas._testing as tm
import numpy as np


@pytest.fixture(params=[True, False])
Expand Down Expand Up @@ -395,3 +396,23 @@ def test_assert_frame_equal_set_mismatch():
msg = r'DataFrame.iloc\[:, 0\] \(column name="set_column"\) values are different'
with pytest.raises(AssertionError, match=msg):
tm.assert_frame_equal(df1, df2)


def test_assert_frame_equal_na_dtype_mismatch():
# GH#61473 - Test that pd.NA values are handled correctly when check_dtype=False
df1 = DataFrame({"a": [pd.NA, 1, 2]}, dtype="Int64")
df2 = DataFrame({"a": [np.nan, 1, 2]}, dtype="float64")

# This should pass with our fix
tm.assert_frame_equal(df1, df2, check_dtype=False)

# This should still fail when check_dtype=True
msg = (
"Attributes of DataFrame\\.iloc\\[:, 0\\] "
'\\(column name="a"\\) are different\n\n'
'Attribute "dtype" are different\n'
"\\[left\\]: Int64\n"
"\\[right\\]: float64"
)
with pytest.raises(AssertionError, match=msg):
tm.assert_frame_equal(df1, df2, check_dtype=True)
Loading