Skip to content

Commit cb8d0fd

Browse files
committed
Make CI.astype('category') not change anything
1 parent 5004347 commit cb8d0fd

File tree

2 files changed

+8
-9
lines changed

2 files changed

+8
-9
lines changed

pandas/core/indexes/category.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -341,21 +341,21 @@ def __array__(self, dtype=None):
341341

342342
@Appender(_index_shared_docs['astype'])
343343
def astype(self, dtype, copy=True):
344+
if isinstance(dtype, compat.string_types) and dtype == 'category':
345+
# GH 18630: CI.astype('category') should not change anything
346+
return self.copy() if copy else self
347+
344348
dtype = pandas_dtype(dtype)
345349
if is_interval_dtype(dtype):
346350
from pandas import IntervalIndex
347351
return IntervalIndex.from_intervals(np.array(self))
348352
elif is_categorical_dtype(dtype):
349-
# want to maintain existing categories/ordered if they are None
353+
# GH 18630: keep current categories if None (ordered can't be None)
350354
if dtype.categories is None:
351355
new_categories = self.categories
352356
else:
353357
new_categories = dtype.categories
354-
if dtype.ordered is None:
355-
new_ordered = self.ordered
356-
else:
357-
new_ordered = dtype.ordered
358-
dtype = CategoricalDtype(new_categories, new_ordered)
358+
dtype = CategoricalDtype(new_categories, dtype.ordered)
359359

360360
# fastpath if dtypes are equal
361361
if dtype == self.dtype:

pandas/tests/indexes/test_category.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -437,10 +437,9 @@ def test_astype_category(self, copy, name, dtype_ordered, index_ordered):
437437
tm.assert_index_equal(result, expected)
438438

439439
if dtype_ordered is False:
440-
# dtype='category' defaults to ordered=False, so only test once
440+
# dtype='category' can't specify ordered, so only test once
441441
result = index.astype('category', copy=copy)
442-
expected = CategoricalIndex(
443-
index.tolist(), categories=index.categories, name=name)
442+
expected = index
444443
tm.assert_index_equal(result, expected)
445444

446445
def test_reindex_base(self):

0 commit comments

Comments
 (0)