Skip to content

Series replace error #59552

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

Merged
merged 11 commits into from
Aug 21, 2024
1 change: 1 addition & 0 deletions doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,7 @@ Other Removals
- Removed the ``method`` keyword in ``ExtensionArray.fillna``, implement ``ExtensionArray._pad_or_backfill`` instead (:issue:`53621`)
- Removed the attribute ``dtypes`` from :class:`.DataFrameGroupBy` (:issue:`51997`)
- Enforced deprecation of ``argmin``, ``argmax``, ``idxmin``, and ``idxmax`` returning a result when ``skipna=False`` and an NA value is encountered or all values are NA values; these operations will now raise in such cases (:issue:`33941`, :issue:`51276`)
- Replaced ``AttributeError`` with ``ValueError`` when using :meth:`Series.replace` with ``dict_like`` and ``dict_like`` (:issue:`59452`)

.. ---------------------------------------------------------------------------
.. _whatsnew_300.performance:
Expand Down
6 changes: 5 additions & 1 deletion pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -7486,9 +7486,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}
is_series = isinstance(self, ABCSeries)
if is_series:
raise ValueError(
"Series.replace cannot use dict-like to_replace dict-like."
)
# 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 = "Series.replace cannot use dict-like to_replace dict-like."
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
Loading