Skip to content

Commit

Permalink
BUG: Copy categorical codes if empty (fixes pandas-dev#18051)
Browse files Browse the repository at this point in the history
rebased to remove conflicts in whats new
  • Loading branch information
Ghasem Naddaf committed Nov 15, 2017
1 parent 148ed63 commit 6c751c0
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 1 deletion.
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.21.1.txt
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ Categorical
- Error messages in the testing module have been improved when items have
different ``CategoricalDtype`` (:issue:`18069`)
- ``CategoricalIndex`` can now correctly take a ``pd.api.types.CategoricalDtype`` as its dtype (:issue:`18116`)
- Bug in ``Categorical.unique()`` returning read-only ``codes`` array when all categories were ``NaN`` (:issue:`18051`)

Other
^^^^^
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -2250,7 +2250,7 @@ def _recode_for_categories(codes, old_categories, new_categories):

if len(old_categories) == 0:
# All null anyway, so just retain the nulls
return codes
return codes.copy()
indexer = coerce_indexer_dtype(new_categories.get_indexer(old_categories),
new_categories)
new_codes = take_1d(indexer, codes.copy(), fill_value=-1)
Expand Down
4 changes: 4 additions & 0 deletions pandas/tests/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -1673,6 +1673,10 @@ def test_unique(self):
exp_cat = Categorical(["b", np.nan, "a"], categories=["b", "a"])
tm.assert_categorical_equal(res, exp_cat)

# GH 18051 unique()._codes should be writeable
cat_nan = Categorical([np.nan])
assert cat_nan.unique()._codes.flags.writeable

def test_unique_ordered(self):
# keep categories order when ordered=True
cat = Categorical(['b', 'a', 'b'], categories=['a', 'b'], ordered=True)
Expand Down

0 comments on commit 6c751c0

Please sign in to comment.