diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 7449c62a5ad31..a4c991dcc166c 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -103,7 +103,7 @@ Bug fixes Categorical ^^^^^^^^^^^ - +- Bug when passing categorical data to :class:`Index` constructor along with ``dtype=object`` incorrectly returning a :class:`CategoricalIndex` instead of object-dtype :class:`Index` (:issue:`32167`) - - diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index c896e68f7a188..53c4dfde2775b 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -304,7 +304,7 @@ def __new__( # Delay import for perf. https://github.com/pandas-dev/pandas/pull/31423 from pandas.core.indexes.category import CategoricalIndex - return CategoricalIndex(data, dtype=dtype, copy=copy, name=name, **kwargs) + return _maybe_asobject(dtype, CategoricalIndex, data, copy, name, **kwargs) # interval elif is_interval_dtype(data) or is_interval_dtype(dtype): diff --git a/pandas/tests/indexes/test_index_new.py b/pandas/tests/indexes/test_index_new.py index e150df971da2d..33f61de6a4ebf 100644 --- a/pandas/tests/indexes/test_index_new.py +++ b/pandas/tests/indexes/test_index_new.py @@ -6,7 +6,7 @@ from pandas.core.dtypes.common import is_unsigned_integer_dtype -from pandas import Index, Int64Index, MultiIndex, UInt64Index +from pandas import CategoricalIndex, Index, Int64Index, MultiIndex, UInt64Index import pandas._testing as tm @@ -47,3 +47,9 @@ def test_constructor_dtypes_to_object(self, cast_index, vals): assert type(index) is Index assert index.dtype == object + + def test_constructor_categorical_to_object(self): + # GH#32167 Categorical data and dtype=object should return object-dtype + ci = CategoricalIndex(range(5)) + result = Index(ci, dtype=object) + assert not isinstance(result, CategoricalIndex)