@@ -202,6 +202,7 @@ class Categorical(PandasObject):
202
202
categorical, read only.
203
203
ordered : boolean
204
204
Whether or not this Categorical is ordered.
205
+ dtype : CategoricalDtype
205
206
206
207
Raises
207
208
------
@@ -248,11 +249,24 @@ class Categorical(PandasObject):
248
249
__array_priority__ = 1000
249
250
_typ = 'categorical'
250
251
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
252
264
253
265
if fastpath :
254
- self ._dtype = CategoricalDtype (categories , ordered )
266
+ if dtype is None :
267
+ dtype = CategoricalDtype (categories , ordered )
255
268
self ._codes = coerce_indexer_dtype (values , categories )
269
+ self ._dtype = dtype
256
270
return
257
271
258
272
# sanitize input
@@ -308,7 +322,8 @@ def __init__(self, values, categories=None, ordered=False, fastpath=False):
308
322
raise NotImplementedError ("> 1 ndim Categorical are not "
309
323
"supported at this time" )
310
324
311
- dtype = CategoricalDtype (categories , ordered )
325
+ if dtype is None or isinstance (dtype , str ):
326
+ dtype = CategoricalDtype (categories , ordered )
312
327
313
328
else :
314
329
# there were two ways if categories are present
@@ -320,7 +335,9 @@ def __init__(self, values, categories=None, ordered=False, fastpath=False):
320
335
321
336
# make sure that we always have the same type here, no matter what
322
337
# we get passed in
323
- dtype = CategoricalDtype (categories , ordered )
338
+ if dtype is None or isinstance (dtype , str ):
339
+ dtype = CategoricalDtype (categories , ordered )
340
+
324
341
codes = _get_codes_for_values (values , dtype .categories )
325
342
326
343
# TODO: check for old style usage. These warnings should be removes
@@ -598,6 +615,9 @@ def _codes_for_groupby(self, sort):
598
615
599
616
return self .reorder_categories (cat .categories )
600
617
618
+ def _set_dtype (self , dtype ):
619
+ return type (self )(self , dtype = dtype , fastpath = True )
620
+
601
621
def set_ordered (self , value , inplace = False ):
602
622
"""
603
623
Sets the ordered attribute to the boolean value
0 commit comments