Skip to content

Commit

Permalink
BUG: reindex would throw when a categorical index was empty pandas-de…
Browse files Browse the repository at this point in the history
  • Loading branch information
ri938 committed Jul 3, 2017
1 parent 664348c commit df5bfcf
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v0.20.3.txt
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ Performance Improvements
Bug Fixes
~~~~~~~~~
- Fixed issue with dataframe scatter plot for categorical data that reports incorrect column key not found when categorical data is used for plotting (:issue:`16199`)

- Handle reindexing an empty categorical index rather than throwing (:issue:`16770`)



Expand Down
9 changes: 7 additions & 2 deletions pandas/core/indexes/category.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,7 +419,11 @@ def reindex(self, target, method=None, level=None, limit=None,
raise ValueError("cannot reindex with a non-unique indexer")

indexer, missing = self.get_indexer_non_unique(np.array(target))
new_target = self.take(indexer)

if len(self.codes):
new_target = self.take(indexer)
else:
new_target = target

# filling in missing if needed
if len(missing):
Expand All @@ -430,7 +434,8 @@ def reindex(self, target, method=None, level=None, limit=None,
result = Index(np.array(self), name=self.name)
new_target, indexer, _ = result._reindex_non_unique(
np.array(target))

# see GH 16819, indexer needs to be converted to correct type
indexer = np.array(indexer, dtype=np.int64)
else:

codes = new_target.codes.copy()
Expand Down
8 changes: 8 additions & 0 deletions pandas/tests/indexes/test_category.py
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,14 @@ def test_reindex_dtype(self):
tm.assert_numpy_array_equal(indexer,
np.array([0, 3, 2], dtype=np.int64))

def test_reindex_empty_index(self):
# See GH16770
c = CategoricalIndex([])
res, indexer = c.reindex(['a', 'b'])
tm.assert_index_equal(res, Index(['a', 'b']), exact=True)
tm.assert_numpy_array_equal(indexer,
np.array([-1, -1], dtype=np.int64))

def test_duplicates(self):

idx = CategoricalIndex([0, 0, 0], name='foo')
Expand Down

0 comments on commit df5bfcf

Please sign in to comment.