Skip to content

Replace with nested dict raises for overlapping keys #27696

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 10 commits into from
Aug 27, 2019
Merged
Show file tree
Hide file tree
Changes from 7 commits
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.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,7 @@ ExtensionArray
Other
^^^^^
- Trying to set the ``display.precision``, ``display.max_rows`` or ``display.max_columns`` using :meth:`set_option` to anything but a ``None`` or a positive int will raise a ``ValueError`` (:issue:`23348`)
- Keeping the consistency in :meth:`DataFrame.replace` behaviour between simple dictionary replacement and nested dictionary replacement (:issue:`27660`)


.. _whatsnew_1000.contributors:
Expand Down
6 changes: 1 addition & 5 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -6642,11 +6642,7 @@ def replace(

for k, v in items:
keys, values = list(zip(*v.items())) or ([], [])
if set(keys) & set(values):
raise ValueError(
"Replacement not allowed with "
"overlapping keys and values"
)

to_rep_dict[k] = list(keys)
value_dict[k] = list(values)

Expand Down
18 changes: 14 additions & 4 deletions pandas/tests/frame/test_replace.py
Original file line number Diff line number Diff line change
Expand Up @@ -1070,17 +1070,27 @@ def test_replace_truthy(self):
assert_frame_equal(r, e)

def test_replace_int_to_int_chain(self):
# GH 27660 keep behaviour consistent for simple dictionary and
# nested dictionary replacement
df = DataFrame({"a": list(range(1, 5))})
with pytest.raises(ValueError, match="Replacement not allowed .+"):
df.replace({"a": dict(zip(range(1, 5), range(2, 6)))})

# nested dictionary replace
result1 = df.replace({"a": dict(zip(range(1, 5), range(2, 6)))})

# simple dictionary replace
result2 = df.replace(dict(zip(range(1, 5), range(2, 6))))

assert_frame_equal(result1, result2)

def test_replace_str_to_str_chain(self):
# GH 27660
a = np.arange(1, 5)
astr = a.astype(str)
bstr = np.arange(2, 6).astype(str)
df = DataFrame({"a": astr})
with pytest.raises(ValueError, match="Replacement not allowed .+"):
df.replace({"a": dict(zip(astr, bstr))})
result1 = df.replace(dict(zip(astr, bstr)))
result2 = df.replace({"a": dict(zip(astr, bstr))})
assert_frame_equal(result1, result2)

def test_replace_swapping_bug(self):
df = pd.DataFrame({"a": [True, False, True]})
Expand Down