Skip to content

Commit df2d9ab

Browse files
gfyoungjorisvandenbossche
authored andcommitted
BUG: Validate the ordered parameter for Categorical (pandas-dev#14059)
Closes pandas-devgh-14058.
1 parent 447df80 commit df2d9ab

File tree

4 files changed

+42
-2
lines changed

4 files changed

+42
-2
lines changed

doc/source/whatsnew/v0.19.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -967,6 +967,7 @@ Bug Fixes
967967
- Bug in ``DataFrame`` assignment with an object-dtyped ``Index`` where the resultant column is mutable to the original object. (:issue:`13522`)
968968
- Bug in matplotlib ``AutoDataFormatter``; this restores the second scaled formatting and re-adds micro-second scaled formatting (:issue:`13131`)
969969
- Bug in selection from a ``HDFStore`` with a fixed format and ``start`` and/or ``stop`` specified will now return the selected range (:issue:`8287`)
970+
- Bug in ``Categorical.from_codes()`` where an unhelpful error was raised when an invalid ``ordered`` parameter was passed in (:issue:`14058`)
970971
- Bug in ``Series`` construction from a tuple of integers on windows not returning default dtype (int64) (:issue:`13646`)
971972

972973
- Bug in ``.groupby(..).resample(..)`` when the same object is called multiple times (:issue:`13174`)

pandas/core/categorical.py

+22-2
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,8 @@ class Categorical(PandasObject):
231231
def __init__(self, values, categories=None, ordered=False,
232232
name=None, fastpath=False):
233233

234+
self._validate_ordered(ordered)
235+
234236
if fastpath:
235237
# fast path
236238
self._codes = _coerce_indexer_dtype(values, categories)
@@ -502,6 +504,25 @@ def _get_labels(self):
502504

503505
_categories = None
504506

507+
@classmethod
508+
def _validate_ordered(cls, ordered):
509+
"""
510+
Validates that we have a valid ordered parameter. If
511+
it is not a boolean, a TypeError will be raised.
512+
513+
Parameters
514+
----------
515+
ordered : object
516+
The parameter to be verified.
517+
518+
Raises
519+
------
520+
TypeError
521+
If 'ordered' is not a boolean.
522+
"""
523+
if not is_bool(ordered):
524+
raise TypeError("'ordered' must either be 'True' or 'False'")
525+
505526
@classmethod
506527
def _validate_categories(cls, categories, fastpath=False):
507528
"""
@@ -588,8 +609,7 @@ def set_ordered(self, value, inplace=False):
588609
Whether or not to set the ordered attribute inplace or return a copy
589610
of this categorical with ordered set to the value
590611
"""
591-
if not is_bool(value):
592-
raise TypeError("ordered must be a boolean value")
612+
self._validate_ordered(value)
593613
cat = self if inplace else self.copy()
594614
cat._ordered = value
595615
if not inplace:

pandas/indexes/category.py

+1
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,7 @@ def _create_categorical(self, data, categories=None, ordered=None):
123123
Categorical
124124
"""
125125
if not isinstance(data, ABCCategorical):
126+
ordered = False if ordered is None else ordered
126127
from pandas.core.categorical import Categorical
127128
data = Categorical(data, categories=categories, ordered=ordered)
128129
else:

pandas/tests/test_categorical.py

+18
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,24 @@ def f():
398398
codes = np.random.choice([0, 1], 5, p=[0.9, 0.1])
399399
pd.Categorical.from_codes(codes, categories=["train", "test"])
400400

401+
def test_validate_ordered(self):
402+
# see gh-14058
403+
exp_msg = "'ordered' must either be 'True' or 'False'"
404+
exp_err = TypeError
405+
406+
# This should be a boolean.
407+
ordered = np.array([0, 1, 2])
408+
409+
with tm.assertRaisesRegexp(exp_err, exp_msg):
410+
Categorical([1, 2, 3], ordered=ordered)
411+
412+
with tm.assertRaisesRegexp(exp_err, exp_msg):
413+
Categorical.from_array([1, 2, 3], ordered=ordered)
414+
415+
with tm.assertRaisesRegexp(exp_err, exp_msg):
416+
Categorical.from_codes([0, 0, 1], categories=['a', 'b', 'c'],
417+
ordered=ordered)
418+
401419
def test_comparisons(self):
402420

403421
result = self.factor[self.factor == 'a']

0 commit comments

Comments
 (0)