Skip to content

Commit 2511df5

Browse files
committed
BUG: TypeError when loc-indexing on a CategoricalIndex with integer categories
1 parent f855025 commit 2511df5

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
@@ -564,6 +564,7 @@ Indexing
564564
- Fix assignment of column via `.loc` with numpy non-ns datetime type (:issue:`27395`)
565565
- Bug in :meth:`Float64Index.astype` where ``np.inf`` was not handled properly when casting to an integer dtype (:issue:`28475`)
566566
- :meth:`Index.union` could fail when the left contained duplicates (:issue:`28257`)
567+
- Bug when indexing with ``.loc`` and the index is a :class:`CateggoricalIndex` with integer categories (:issue:`17569`)
567568
- :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`)
568569
- Bug in :meth:`Float64Index.get_loc` incorrectly raising ``TypeError`` instead of ``KeyError`` (:issue:`29189`)
569570

pandas/core/indexes/category.py

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

697697
@Appender(_index_shared_docs["_convert_scalar_indexer"])
698698
def _convert_scalar_indexer(self, key, kind=None):
699-
if self.categories._defer_to_indexing:
699+
if kind == "loc" or self.categories._defer_to_indexing:
700700
return self.categories._convert_scalar_indexer(key, kind=kind)
701701

702702
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)