Skip to content

Backport PR #27932 on branch 0.25.x (BUG: Ensure that fill_na in Categorical only replaces null values) #27947

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
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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v0.25.1.rst
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ Bug fixes
Categorical
^^^^^^^^^^^

-
- Bug in :meth:`Categorical.fillna` would replace all values, not just those that are ``NaN`` (:issue:`26215`)
-
-

Expand Down
4 changes: 2 additions & 2 deletions pandas/core/arrays/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -1864,8 +1864,8 @@ def fillna(self, value=None, method=None, limit=None):
raise ValueError("fill value must be in categories")

values_codes = _get_codes_for_values(value, self.categories)
indexer = np.where(values_codes != -1)
codes[indexer] = values_codes[values_codes != -1]
indexer = np.where(codes == -1)
codes[indexer] = values_codes[indexer]

# If value is not a dict or Series it should be a scalar
elif is_hashable(value):
Expand Down
22 changes: 22 additions & 0 deletions pandas/tests/series/test_missing.py
Original file line number Diff line number Diff line change
Expand Up @@ -578,6 +578,28 @@ def test_fillna_categorical(self, fill_value, expected_output):
exp = Series(Categorical(expected_output, categories=["a", "b"]))
tm.assert_series_equal(s.fillna(fill_value), exp)

@pytest.mark.parametrize(
"fill_value, expected_output",
[
(Series(["a", "b", "c", "d", "e"]), ["a", "b", "b", "d", "e"]),
(Series(["b", "d", "a", "d", "a"]), ["a", "d", "b", "d", "a"]),
(
Series(
Categorical(
["b", "d", "a", "d", "a"], categories=["b", "c", "d", "e", "a"]
)
),
["a", "d", "b", "d", "a"],
),
],
)
def test_fillna_categorical_with_new_categories(self, fill_value, expected_output):
# GH 26215
data = ["a", np.nan, "b", np.nan, np.nan]
s = Series(Categorical(data, categories=["a", "b", "c", "d", "e"]))
exp = Series(Categorical(expected_output, categories=["a", "b", "c", "d", "e"]))
tm.assert_series_equal(s.fillna(fill_value), exp)

def test_fillna_categorical_raise(self):
data = ["a", np.nan, "b", np.nan, np.nan]
s = Series(Categorical(data, categories=["a", "b"]))
Expand Down