Skip to content

Commit c57f6e7

Browse files
committed
API/CLN: simplify CategoricalBlock.replace (pandas-dev#33279)
1 parent ed862c0 commit c57f6e7

File tree

2 files changed

+12
-15
lines changed

2 files changed

+12
-15
lines changed

pandas/core/internals/blocks.py

+3-12
Original file line numberDiff line numberDiff line change
@@ -2753,18 +2753,9 @@ def replace(
27532753
):
27542754
inplace = validate_bool_kwarg(inplace, "inplace")
27552755
result = self if inplace else self.copy()
2756-
if filter is None: # replace was called on a series
2757-
result.values.replace(to_replace, value, inplace=True)
2758-
if convert:
2759-
return result.convert(numeric=False, copy=not inplace)
2760-
else:
2761-
return result
2762-
else: # replace was called on a DataFrame
2763-
if not isna(value):
2764-
result.values.add_categories(value, inplace=True)
2765-
return super(CategoricalBlock, result).replace(
2766-
to_replace, value, inplace, filter, regex, convert
2767-
)
2756+
2757+
result.values.replace(to_replace, value, inplace=True)
2758+
return result
27682759

27692760

27702761
# -----------------------------------------------------------------

pandas/tests/frame/methods/test_replace.py

+9-3
Original file line numberDiff line numberDiff line change
@@ -1303,9 +1303,15 @@ def test_replace_method(self, to_replace, method, expected):
13031303
def test_categorical_replace_with_dict(self, replace_dict, final_data):
13041304
# GH 26988
13051305
df = DataFrame([[1, 1], [2, 2]], columns=["a", "b"], dtype="category")
1306-
expected = DataFrame(final_data, columns=["a", "b"], dtype="category")
1307-
expected["a"] = expected["a"].cat.set_categories([1, 2, 3])
1308-
expected["b"] = expected["b"].cat.set_categories([1, 2, 3])
1306+
1307+
final_data = np.array(final_data)
1308+
1309+
a = pd.Categorical(final_data[:, 0], categories=[3, 2])
1310+
1311+
excat = [3, 2] if replace_dict["b"] == 1 else [1, 3]
1312+
b = pd.Categorical(final_data[:, 1], categories=excat)
1313+
1314+
expected = DataFrame({"a": a, "b": b})
13091315
result = df.replace(replace_dict, 3)
13101316
tm.assert_frame_equal(result, expected)
13111317
with pytest.raises(AssertionError):

0 commit comments

Comments
 (0)