Skip to content

Commit 67ef906

Browse files
jbrockmendelmathurk1tkmz-n
authored and
Kevin D Smith
committed
BUG: NDFrame.replace wrong exception type, wrong return when size==0 (pandas-dev#36045)
* REF: remove unnecesary try/except * TST: add test for agg on ordered categorical cols (pandas-dev#35630) * TST: resample does not yield empty groups (pandas-dev#10603) (pandas-dev#35799) * revert accidental rebase * BUG: NDFrame.replace wrong exception type, wrong return when size==0 * bool->bool_t * whatsnew Co-authored-by: Karthik Mathur <[email protected]> Co-authored-by: tkmz-n <[email protected]>
1 parent 3937b82 commit 67ef906

File tree

3 files changed

+32
-7
lines changed

3 files changed

+32
-7
lines changed

doc/source/whatsnew/v1.2.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,7 @@ ExtensionArray
282282

283283
Other
284284
^^^^^
285-
-
285+
- Bug in :meth:`DataFrame.replace` and :meth:`Series.replace` incorrectly raising ``AssertionError`` instead of ``ValueError`` when invalid parameter combinations are passed (:issue:`36045`)
286286
-
287287

288288
.. ---------------------------------------------------------------------------

pandas/core/generic.py

+8-6
Original file line numberDiff line numberDiff line change
@@ -6179,8 +6179,8 @@ def replace(
61796179
self,
61806180
to_replace=None,
61816181
value=None,
6182-
inplace=False,
6183-
limit=None,
6182+
inplace: bool_t = False,
6183+
limit: Optional[int] = None,
61846184
regex=False,
61856185
method="pad",
61866186
):
@@ -6256,7 +6256,7 @@ def replace(
62566256
If True, in place. Note: this will modify any
62576257
other views on this object (e.g. a column from a DataFrame).
62586258
Returns the caller if this is True.
6259-
limit : int, default None
6259+
limit : int or None, default None
62606260
Maximum size gap to forward or backward fill.
62616261
regex : bool or same types as `to_replace`, default False
62626262
Whether to interpret `to_replace` and/or `value` as regular
@@ -6490,7 +6490,7 @@ def replace(
64906490

64916491
inplace = validate_bool_kwarg(inplace, "inplace")
64926492
if not is_bool(regex) and to_replace is not None:
6493-
raise AssertionError("'to_replace' must be 'None' if 'regex' is not a bool")
6493+
raise ValueError("'to_replace' must be 'None' if 'regex' is not a bool")
64946494

64956495
if value is None:
64966496
# passing a single value that is scalar like
@@ -6550,12 +6550,14 @@ def replace(
65506550

65516551
# need a non-zero len on all axes
65526552
if not self.size:
6553-
return self
6553+
if inplace:
6554+
return
6555+
return self.copy()
65546556

65556557
if is_dict_like(to_replace):
65566558
if is_dict_like(value): # {'A' : NA} -> {'A' : 0}
65576559
# Note: Checking below for `in foo.keys()` instead of
6558-
# `in foo`is needed for when we have a Series and not dict
6560+
# `in foo` is needed for when we have a Series and not dict
65596561
mapping = {
65606562
col: (to_replace[col], value[col])
65616563
for col in to_replace.keys()

pandas/tests/series/methods/test_replace.py

+23
Original file line numberDiff line numberDiff line change
@@ -397,6 +397,29 @@ def test_replace_invalid_to_replace(self):
397397
with pytest.raises(TypeError, match=msg):
398398
series.replace(lambda x: x.strip())
399399

400+
@pytest.mark.parametrize("frame", [False, True])
401+
def test_replace_nonbool_regex(self, frame):
402+
obj = pd.Series(["a", "b", "c "])
403+
if frame:
404+
obj = obj.to_frame()
405+
406+
msg = "'to_replace' must be 'None' if 'regex' is not a bool"
407+
with pytest.raises(ValueError, match=msg):
408+
obj.replace(to_replace=["a"], regex="foo")
409+
410+
@pytest.mark.parametrize("frame", [False, True])
411+
def test_replace_empty_copy(self, frame):
412+
obj = pd.Series([], dtype=np.float64)
413+
if frame:
414+
obj = obj.to_frame()
415+
416+
res = obj.replace(4, 5, inplace=True)
417+
assert res is None
418+
419+
res = obj.replace(4, 5, inplace=False)
420+
tm.assert_equal(res, obj)
421+
assert res is not obj
422+
400423
def test_replace_only_one_dictlike_arg(self):
401424
# GH#33340
402425

0 commit comments

Comments
 (0)