|
19 | 19 | is_scalar,
|
20 | 20 | )
|
21 | 21 | from pandas.core.dtypes.dtypes import CategoricalDtype
|
| 22 | +from pandas.core.dtypes.generic import ABCSeries |
22 | 23 | from pandas.core.dtypes.missing import isna
|
23 | 24 |
|
24 | 25 | from pandas.core import accessor
|
|
30 | 31 | from pandas.core.indexes.extension import ExtensionIndex, inherit_names
|
31 | 32 | import pandas.core.missing as missing
|
32 | 33 | from pandas.core.ops import get_op_result_name
|
| 34 | +from pandas.core.construction import extract_array |
33 | 35 |
|
34 | 36 | _index_doc_kwargs = dict(ibase._index_doc_kwargs)
|
35 | 37 | _index_doc_kwargs.update(dict(target_klass="CategoricalIndex"))
|
@@ -198,8 +200,14 @@ def __new__(
|
198 | 200 | data = []
|
199 | 201 |
|
200 | 202 | assert isinstance(dtype, CategoricalDtype), dtype
|
201 |
| - if not isinstance(data, Categorical) or data.dtype != dtype: |
| 203 | + if isinstance(data, (cls, ABCSeries)) and is_categorical_dtype(data): |
| 204 | + data = extract_array(data) |
| 205 | + |
| 206 | + if not isinstance(data, Categorical): |
202 | 207 | data = Categorical(data, dtype=dtype)
|
| 208 | + elif isinstance(dtype, CategoricalDtype) and dtype != data.dtype: |
| 209 | + # we want to silently ignore dtype='category' |
| 210 | + data = data._set_dtype(dtype) |
203 | 211 |
|
204 | 212 | data = data.copy() if copy else data
|
205 | 213 |
|
|
0 commit comments