Skip to content

Commit d3eb071

Browse files
committed
BUG: TypeError when loc-indexing on a CategoricalIndex with integer categories
1 parent 3f69d62 commit d3eb071

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

doc/source/whatsnew/v1.0.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -521,6 +521,7 @@ Indexing
521521
- Fix assignment of column via `.loc` with numpy non-ns datetime type (:issue:`27395`)
522522
- Bug in :meth:`Float64Index.astype` where ``np.inf`` was not handled properly when casting to an integer dtype (:issue:`28475`)
523523
- :meth:`Index.union` could fail when the left contained duplicates (:issue:`28257`)
524+
- Bug when indexing with ``.loc`` and the index is a :class:`CateggoricalIndex` with integer categories (:issue:`17569`)
524525
- :meth:`Index.get_indexer_non_unique` could fail with `TypeError` in some cases, such as when searching for ints in a string index (:issue:`28257`)
525526
-
526527

pandas/core/indexes/category.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -708,7 +708,7 @@ def get_indexer_non_unique(self, target):
708708

709709
@Appender(_index_shared_docs["_convert_scalar_indexer"])
710710
def _convert_scalar_indexer(self, key, kind=None):
711-
if self.categories._defer_to_indexing:
711+
if kind == "loc" or self.categories._defer_to_indexing:
712712
return self.categories._convert_scalar_indexer(key, kind=kind)
713713

714714
return super()._convert_scalar_indexer(key, kind=kind)

pandas/tests/indexing/test_categorical.py

+23
Original file line numberDiff line numberDiff line change
@@ -754,3 +754,26 @@ def test_map_with_dict_or_series(self):
754754
output = cur_index.map(mapper)
755755
# Order of categories in output can be different
756756
tm.assert_index_equal(expected, output)
757+
758+
def test_indexing_with_integer_categories(self):
759+
# GH-17569
760+
cat_idx = CategoricalIndex([1, 2, 3])
761+
cat = DataFrame({"A": ["foo", "bar", "baz"]}, index=cat_idx)
762+
# scalar
763+
result = cat.loc[1]
764+
expected = Series(["foo"], index=["A"], name=1)
765+
tm.assert_series_equal(result, expected)
766+
# list
767+
result = cat.loc[[1, 2]]
768+
expected = DataFrame(["foo", "bar"], index=cat_idx[:2], columns=["A"])
769+
tm.assert_frame_equal(result, expected)
770+
# scalar assignment
771+
result = cat.copy()
772+
result.loc[1] = "qux"
773+
expected = DataFrame({"A": ["qux", "bar", "baz"]}, index=cat_idx)
774+
tm.assert_frame_equal(result, expected)
775+
# list assignment
776+
result = cat.copy()
777+
result.loc[[1, 2], "A"] = ["qux", "qux2"]
778+
expected = DataFrame({"A": ["qux", "qux2", "baz"]}, index=cat_idx)
779+
tm.assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)