Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
15 changes: 3 additions & 12 deletions pandas/core/internals/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -2761,18 +2761,9 @@ def replace(
):
inplace = validate_bool_kwarg(inplace, "inplace")
result = self if inplace else self.copy()
if filter is None: # replace was called on a series
result.values.replace(to_replace, value, inplace=True)
if convert:
return result.convert(numeric=False, copy=not inplace)
else:
return result
else: # replace was called on a DataFrame
if not isna(value):
result.values.add_categories(value, inplace=True)
return super(CategoricalBlock, result).replace(
to_replace, value, inplace, filter, regex, convert
)

result.values.replace(to_replace, value, inplace=True)
return result


# -----------------------------------------------------------------
Expand Down
12 changes: 9 additions & 3 deletions pandas/tests/frame/methods/test_replace.py
Original file line number Diff line number Diff line change
Expand Up @@ -1303,9 +1303,15 @@ def test_replace_method(self, to_replace, method, expected):
def test_categorical_replace_with_dict(self, replace_dict, final_data):
# GH 26988
df = DataFrame([[1, 1], [2, 2]], columns=["a", "b"], dtype="category")
expected = DataFrame(final_data, columns=["a", "b"], dtype="category")
expected["a"] = expected["a"].cat.set_categories([1, 2, 3])
expected["b"] = expected["b"].cat.set_categories([1, 2, 3])

final_data = np.array(final_data)

a = pd.Categorical(final_data[:, 0], categories=[3, 2])

excat = [3, 2] if replace_dict["b"] == 1 else [1, 3]
b = pd.Categorical(final_data[:, 1], categories=excat)

expected = DataFrame({"a": a, "b": b})
result = df.replace(replace_dict, 3)
tm.assert_frame_equal(result, expected)
with pytest.raises(AssertionError):
Expand Down