|
19 | 19 | is_scalar,
|
20 | 20 | )
|
21 | 21 | from pandas.core.dtypes.dtypes import CategoricalDtype
|
22 |
| -from pandas.core.dtypes.generic import ABCCategorical, ABCSeries |
23 | 22 | from pandas.core.dtypes.missing import isna
|
24 | 23 |
|
25 | 24 | from pandas.core import accessor
|
@@ -195,7 +194,9 @@ def __new__(
|
195 | 194 | raise cls._scalar_data_error(data)
|
196 | 195 | data = []
|
197 | 196 |
|
198 |
| - data = cls._create_categorical(data, dtype=dtype) |
| 197 | + assert isinstance(dtype, CategoricalDtype), dtype |
| 198 | + if not isinstance(data, Categorical) or data.dtype != dtype: |
| 199 | + data = Categorical(data, dtype=dtype) |
199 | 200 |
|
200 | 201 | data = data.copy() if copy else data
|
201 | 202 |
|
@@ -225,37 +226,11 @@ def _create_from_codes(self, codes, dtype=None, name=None):
|
225 | 226 | return CategoricalIndex(cat, name=name)
|
226 | 227 |
|
227 | 228 | @classmethod
|
228 |
| - def _create_categorical(cls, data, dtype=None): |
229 |
| - """ |
230 |
| - *this is an internal non-public method* |
231 |
| -
|
232 |
| - create the correct categorical from data and the properties |
233 |
| -
|
234 |
| - Parameters |
235 |
| - ---------- |
236 |
| - data : data for new Categorical |
237 |
| - dtype : CategoricalDtype, defaults to existing |
238 |
| -
|
239 |
| - Returns |
240 |
| - ------- |
241 |
| - Categorical |
242 |
| - """ |
243 |
| - if isinstance(data, (cls, ABCSeries)) and is_categorical_dtype(data): |
244 |
| - data = data.values |
245 |
| - |
246 |
| - if not isinstance(data, ABCCategorical): |
247 |
| - return Categorical(data, dtype=dtype) |
248 |
| - |
249 |
| - if isinstance(dtype, CategoricalDtype) and dtype != data.dtype: |
250 |
| - # we want to silently ignore dtype='category' |
251 |
| - data = data._set_dtype(dtype) |
252 |
| - return data |
253 |
| - |
254 |
| - @classmethod |
255 |
| - def _simple_new(cls, values, name=None, dtype=None): |
| 229 | + def _simple_new(cls, values: Categorical, name=None, dtype=None): |
| 230 | + # GH#32204 dtype is included for compat with Index._simple_new |
| 231 | + assert isinstance(values, Categorical), type(values) |
256 | 232 | result = object.__new__(cls)
|
257 | 233 |
|
258 |
| - values = cls._create_categorical(values, dtype=dtype) |
259 | 234 | result._data = values
|
260 | 235 | result.name = name
|
261 | 236 |
|
@@ -298,7 +273,8 @@ def _is_dtype_compat(self, other) -> bool:
|
298 | 273 | values = other
|
299 | 274 | if not is_list_like(values):
|
300 | 275 | values = [values]
|
301 |
| - other = CategoricalIndex(self._create_categorical(other, dtype=self.dtype)) |
| 276 | + cat = Categorical(other, dtype=self.dtype) |
| 277 | + other = CategoricalIndex(cat) |
302 | 278 | if not other.isin(values).all():
|
303 | 279 | raise TypeError(
|
304 | 280 | "cannot append a non-category item to a CategoricalIndex"
|
|
0 commit comments