Skip to content

Commit e692e32

Browse files
committed
accept dtype
1 parent 5af0173 commit e692e32

File tree

1 file changed

+24
-4
lines changed

1 file changed

+24
-4
lines changed

pandas/core/categorical.py

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,7 @@ class Categorical(PandasObject):
202202
categorical, read only.
203203
ordered : boolean
204204
Whether or not this Categorical is ordered.
205+
dtype : CategoricalDtype
205206
206207
Raises
207208
------
@@ -248,11 +249,24 @@ class Categorical(PandasObject):
248249
__array_priority__ = 1000
249250
_typ = 'categorical'
250251

251-
def __init__(self, values, categories=None, ordered=False, fastpath=False):
252+
def __init__(self, values, categories=None, ordered=None, dtype=None,
253+
fastpath=False):
254+
255+
if dtype is not None:
256+
if categories is not None or ordered is not None:
257+
raise ValueError("Cannot specify both `dtype` and `categories`"
258+
" or `ordered`.")
259+
categories = dtype.categories
260+
ordered = dtype.ordered
261+
262+
if ordered is None:
263+
ordered = False
252264

253265
if fastpath:
254-
self._dtype = CategoricalDtype(categories, ordered)
266+
if dtype is None:
267+
dtype = CategoricalDtype(categories, ordered)
255268
self._codes = coerce_indexer_dtype(values, categories)
269+
self._dtype = dtype
256270
return
257271

258272
# sanitize input
@@ -308,7 +322,8 @@ def __init__(self, values, categories=None, ordered=False, fastpath=False):
308322
raise NotImplementedError("> 1 ndim Categorical are not "
309323
"supported at this time")
310324

311-
dtype = CategoricalDtype(categories, ordered)
325+
if dtype is None or isinstance(dtype, str):
326+
dtype = CategoricalDtype(categories, ordered)
312327

313328
else:
314329
# there were two ways if categories are present
@@ -320,7 +335,9 @@ def __init__(self, values, categories=None, ordered=False, fastpath=False):
320335

321336
# make sure that we always have the same type here, no matter what
322337
# we get passed in
323-
dtype = CategoricalDtype(categories, ordered)
338+
if dtype is None or isinstance(dtype, str):
339+
dtype = CategoricalDtype(categories, ordered)
340+
324341
codes = _get_codes_for_values(values, dtype.categories)
325342

326343
# TODO: check for old style usage. These warnings should be removes
@@ -598,6 +615,9 @@ def _codes_for_groupby(self, sort):
598615

599616
return self.reorder_categories(cat.categories)
600617

618+
def _set_dtype(self, dtype):
619+
return type(self)(self, dtype=dtype, fastpath=True)
620+
601621
def set_ordered(self, value, inplace=False):
602622
"""
603623
Sets the ordered attribute to the boolean value

0 commit comments

Comments
 (0)