Skip to content

Commit 7ed7d7c

Browse files
mroeschkepmhatre1
authored andcommitted
PERF: Categorical(range).categories returns RangeIndex instead of Index (pandas-dev#57787)
1 parent 0ec61e5 commit 7ed7d7c

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

doc/source/whatsnew/v3.0.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,7 @@ Removal of prior version deprecations/changes
256256

257257
Performance improvements
258258
~~~~~~~~~~~~~~~~~~~~~~~~
259+
- :attr:`Categorical.categories` returns a :class:`RangeIndex` columns instead of an :class:`Index` if the constructed ``values`` was a ``range``. (:issue:`57787`)
259260
- :func:`concat` returns a :class:`RangeIndex` level in the :class:`MultiIndex` result when ``keys`` is a ``range`` or :class:`RangeIndex` (:issue:`57542`)
260261
- :meth:`RangeIndex.append` returns a :class:`RangeIndex` instead of a :class:`Index` when appending values that could continue the :class:`RangeIndex` (:issue:`57467`)
261262
- :meth:`Series.str.extract` returns a :class:`RangeIndex` columns instead of an :class:`Index` column when possible (:issue:`57542`)

pandas/core/arrays/categorical.py

+4
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,10 @@ def __init__(
431431
if isinstance(vdtype, CategoricalDtype):
432432
if dtype.categories is None:
433433
dtype = CategoricalDtype(values.categories, dtype.ordered)
434+
elif isinstance(values, range):
435+
from pandas.core.indexes.range import RangeIndex
436+
437+
values = RangeIndex(values)
434438
elif not isinstance(values, (ABCIndex, ABCSeries, ExtensionArray)):
435439
values = com.convert_to_list_like(values)
436440
if isinstance(values, list) and len(values) == 0:

pandas/tests/arrays/categorical/test_constructors.py

+15
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
IntervalIndex,
2525
MultiIndex,
2626
NaT,
27+
RangeIndex,
2728
Series,
2829
Timestamp,
2930
date_range,
@@ -779,3 +780,17 @@ def test_constructor_preserves_freq(self):
779780
result = cat.categories.freq
780781

781782
assert expected == result
783+
784+
@pytest.mark.parametrize(
785+
"values, categories",
786+
[
787+
[range(5), None],
788+
[range(4), range(5)],
789+
[[0, 1, 2, 3], range(5)],
790+
[[], range(5)],
791+
],
792+
)
793+
def test_range_values_preserves_rangeindex_categories(self, values, categories):
794+
result = Categorical(values=values, categories=categories).categories
795+
expected = RangeIndex(range(5))
796+
tm.assert_index_equal(result, expected, exact=True)

0 commit comments

Comments
 (0)