Skip to content

Commit f2ff20d

Browse files
committed
BUG: RecursionError when attempting to replace "np.nan" values under main branch (pandas-dev#45725)
1 parent 2ff7dc0 commit f2ff20d

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-0
lines changed

pandas/core/internals/blocks.py

+1
Original file line numberDiff line numberDiff line change
@@ -669,6 +669,7 @@ def replace(
669669
# go through replace_list
670670

671671
values = self.values
672+
value = self._standardize_fill_value(value) # GH#45725
672673

673674
if isinstance(values, Categorical):
674675
# TODO: avoid special-casing

pandas/tests/frame/methods/test_replace.py

+12
Original file line numberDiff line numberDiff line change
@@ -661,6 +661,18 @@ def test_replace_simple_nested_dict_with_nonexistent_value(self):
661661
result = df.replace({"col": {-1: "-", 1: "a", 4: "b"}})
662662
tm.assert_frame_equal(expected, result)
663663

664+
def test_replace_numpy_nan(self):
665+
# GH#45725 ensure np.nan can be replaced with pd.NA
666+
df = pd.DataFrame({"A": [np.nan], "B": [np.nan]}, dtype=object)
667+
result = df.replace({np.nan: pd.NA})
668+
expected = pd.DataFrame({"A": [pd.NA], "B": [pd.NA]}, dtype=object)
669+
tm.assert_frame_equal(result, expected)
670+
671+
# same thing but with None
672+
result = df.replace({np.nan: None})
673+
expected = pd.DataFrame({"A": [None], "B": [None]}, dtype=object)
674+
tm.assert_frame_equal(result, expected)
675+
664676
def test_replace_value_is_none(self, datetime_frame):
665677
orig_value = datetime_frame.iloc[0, 0]
666678
orig2 = datetime_frame.iloc[1, 0]

pandas/tests/series/methods/test_replace.py

+14
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,20 @@ def test_replace_explicit_none(self):
3636
assert expected.iloc[-1] is None
3737
tm.assert_series_equal(result, expected)
3838

39+
def test_replace_numpy_nan(self):
40+
# GH#45725 ensure np.nan can be replaced
41+
ser = pd.Series([np.nan, np.nan], dtype=object)
42+
result = ser.replace({np.nan: pd.NA})
43+
expected = pd.Series([pd.NA, pd.NA], dtype=object)
44+
tm.assert_series_equal(result, expected)
45+
assert result.dtype == object
46+
47+
# same thing but with None
48+
result = ser.replace({np.nan: None})
49+
expected = pd.Series([None, None], dtype=object)
50+
tm.assert_series_equal(result, expected)
51+
assert result.dtype == object
52+
3953
def test_replace_noop_doesnt_downcast(self):
4054
# GH#44498
4155
ser = pd.Series([None, None, pd.Timestamp("2021-12-16 17:31")], dtype=object)

0 commit comments

Comments
 (0)