Skip to content

Commit

Permalink
Series replace error (#59552)
Browse files Browse the repository at this point in the history
* changed AttributeError to ValueError

* added test for replace method from dict_like to dict_like for a pd.Series

* added entry in whatsnew.rst

* Update doc/source/whatsnew/v3.0.0.rst

removed rst entry

Co-authored-by: Matthew Roeschke <10647082+mroeschke@users.noreply.github.com>

* Update pandas/core/generic.py

Co-authored-by: Matthew Roeschke <10647082+mroeschke@users.noreply.github.com>

* Update pandas/core/generic.py

Co-authored-by: Matthew Roeschke <10647082+mroeschke@users.noreply.github.com>

* updated msg test function

* breaking line for 88 instead of 89 characters

---------

Co-authored-by: Matthew Roeschke <10647082+mroeschke@users.noreply.github.com>
  • Loading branch information
fbourgey and mroeschke authored Aug 21, 2024
1 parent e1a79b2 commit 320d613
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
6 changes: 5 additions & 1 deletion pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -7487,9 +7487,13 @@ def replace(
if inplace:
return None
return self.copy(deep=False)

if is_dict_like(to_replace):
if is_dict_like(value): # {'A' : NA} -> {'A' : 0}
if isinstance(self, ABCSeries):
raise ValueError(
"to_replace and value cannot be dict-like for "
"Series.replace"
)
# Note: Checking below for `in foo.keys()` instead of
# `in foo` is needed for when we have a Series and not dict
mapping = {
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/series/methods/test_replace.py
Original file line number Diff line number Diff line change
Expand Up @@ -496,6 +496,15 @@ def test_replace_only_one_dictlike_arg(self, fixed_now_ts):
with pytest.raises(ValueError, match=msg):
ser.replace(to_replace, value)

def test_replace_dict_like_with_dict_like(self):
# GH 59452
s = pd.Series([1, 2, 3, 4, 5])
to_replace = pd.Series([1])
value = pd.Series([75])
msg = "to_replace and value cannot be dict-like for Series.replace"
with pytest.raises(ValueError, match=msg):
s.replace(to_replace, value)

def test_replace_extension_other(self, frame_or_series):
# https://github.com/pandas-dev/pandas/issues/34530
obj = frame_or_series(pd.array([1, 2, 3], dtype="Int64"))
Expand Down

0 comments on commit 320d613

Please sign in to comment.