Skip to content

BUG/TST fix replace with panda NAType #47480 #47688

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

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -910,6 +910,7 @@ Missing
- Bug in :meth:`Series.fillna` and :meth:`DataFrame.fillna` with :class:`IntervalDtype` and incompatible value raising instead of casting to a common (usually object) dtype (:issue:`45796`)
- Bug in :meth:`DataFrame.interpolate` with object-dtype column not returning a copy with ``inplace=False`` (:issue:`45791`)
- Bug in :meth:`DataFrame.dropna` allows to set both ``how`` and ``thresh`` incompatible arguments (:issue:`46575`)
- Bug in :meth:`DataFrame.replace` now works when ``pandas.NA`` is a value in the dara frame (:issue:`47480`)

MultiIndex
^^^^^^^^^^
Expand Down
14 changes: 13 additions & 1 deletion pandas/core/missing.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,19 @@ def mask_missing(arr: ArrayLike, values_to_mask) -> npt.NDArray[np.bool_]:
# GH#29553 prevent numpy deprecation warnings
pass
else:
new_mask = arr == x
# Numpy Currently can't handle comparisons with "NAType" instances
arr_shape = arr.shape
arr = np.array(arr)
arr = arr.flatten()
new_mask = np.array([])
for i in arr:
if isna(i):
new_mask = np.append(new_mask, False)
else:
new_mask = np.append(new_mask, x == i)
new_mask.shape = arr_shape
new_mask = new_mask == 1

if not isinstance(new_mask, np.ndarray):
# usually BooleanArray
new_mask = new_mask.to_numpy(dtype=bool, na_value=False)
Expand Down
7 changes: 7 additions & 0 deletions pandas/tests/frame/methods/test_replace.py
Original file line number Diff line number Diff line change
Expand Up @@ -1567,3 +1567,10 @@ def test_replace_with_value_also_being_replaced(self):
result = df.replace({0: 1, 1: np.nan})
expected = DataFrame({"A": [1, np.nan, 2], "B": [np.nan, 1, 2]})
tm.assert_frame_equal(result, expected)

def test_replace_with_pandas_NA(self):
# GH47480
df = DataFrame({"A": [pd.NA, 1, 2], "B": [1, 0, 2]})
result = df.replace(2, 3)
expected = DataFrame({"A": [pd.NA, 1, 3], "B": [1, 0, 3]})
tm.assert_frame_equal(result, expected)