Skip to content

Commit 6c751c0

Browse files
author
Ghasem Naddaf
committed
BUG: Copy categorical codes if empty (fixes pandas-dev#18051)
rebased to remove conflicts in whats new
1 parent 148ed63 commit 6c751c0

File tree

3 files changed

+6
-1
lines changed

3 files changed

+6
-1
lines changed

doc/source/whatsnew/v0.21.1.txt

+1
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,7 @@ Categorical
130130
- Error messages in the testing module have been improved when items have
131131
different ``CategoricalDtype`` (:issue:`18069`)
132132
- ``CategoricalIndex`` can now correctly take a ``pd.api.types.CategoricalDtype`` as its dtype (:issue:`18116`)
133+
- Bug in ``Categorical.unique()`` returning read-only ``codes`` array when all categories were ``NaN`` (:issue:`18051`)
133134

134135
Other
135136
^^^^^

pandas/core/categorical.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2250,7 +2250,7 @@ def _recode_for_categories(codes, old_categories, new_categories):
22502250

22512251
if len(old_categories) == 0:
22522252
# All null anyway, so just retain the nulls
2253-
return codes
2253+
return codes.copy()
22542254
indexer = coerce_indexer_dtype(new_categories.get_indexer(old_categories),
22552255
new_categories)
22562256
new_codes = take_1d(indexer, codes.copy(), fill_value=-1)

pandas/tests/test_categorical.py

+4
Original file line numberDiff line numberDiff line change
@@ -1673,6 +1673,10 @@ def test_unique(self):
16731673
exp_cat = Categorical(["b", np.nan, "a"], categories=["b", "a"])
16741674
tm.assert_categorical_equal(res, exp_cat)
16751675

1676+
# GH 18051 unique()._codes should be writeable
1677+
cat_nan = Categorical([np.nan])
1678+
assert cat_nan.unique()._codes.flags.writeable
1679+
16761680
def test_unique_ordered(self):
16771681
# keep categories order when ordered=True
16781682
cat = Categorical(['b', 'a', 'b'], categories=['a', 'b'], ordered=True)

0 commit comments

Comments
 (0)