diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index fbd2c2b5345fc..3a8fa7798a2d5 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -170,7 +170,7 @@ Bug fixes Categorical ^^^^^^^^^^^ - +- Bug in :class:`CategoricalIndex` incorrectly failing to raise ``TypeError`` when scalar data is passed (:issue:`38614`) - Bug in ``CategoricalIndex.reindex`` failed when ``Index`` passed with elements all in category (:issue:`28690`) - diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 059c36a901297..9062667298d7c 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -186,11 +186,7 @@ def __new__( name = maybe_extract_name(name, data, cls) if is_scalar(data): - # don't allow scalars - # if data is None, then categories must be provided - if data is not None or categories is None: - raise cls._scalar_data_error(data) - data = [] + raise cls._scalar_data_error(data) data = Categorical( data, categories=categories, ordered=ordered, dtype=dtype, copy=copy diff --git a/pandas/tests/indexes/categorical/test_category.py b/pandas/tests/indexes/categorical/test_category.py index 00fca00c5b4a0..2119600887ba4 100644 --- a/pandas/tests/indexes/categorical/test_category.py +++ b/pandas/tests/indexes/categorical/test_category.py @@ -91,7 +91,7 @@ def test_insert(self): tm.assert_index_equal(result, expected, exact=True) # test empty - result = CategoricalIndex(categories=categories).insert(0, "a") + result = CategoricalIndex([], categories=categories).insert(0, "a") expected = CategoricalIndex(["a"], categories=categories) tm.assert_index_equal(result, expected, exact=True) diff --git a/pandas/tests/indexes/categorical/test_constructors.py b/pandas/tests/indexes/categorical/test_constructors.py index ee3f85da22781..aeb31b710ddbb 100644 --- a/pandas/tests/indexes/categorical/test_constructors.py +++ b/pandas/tests/indexes/categorical/test_constructors.py @@ -6,6 +6,11 @@ class TestCategoricalIndexConstructors: + def test_construction_disallows_scalar(self): + msg = "must be called with a collection of some kind" + with pytest.raises(TypeError, match=msg): + CategoricalIndex(categories=list("abcd"), ordered=False) + def test_construction(self): ci = CategoricalIndex(list("aabbca"), categories=list("abcd"), ordered=False) @@ -20,7 +25,7 @@ def test_construction(self): assert not result.ordered # empty - result = CategoricalIndex(categories=categories) + result = CategoricalIndex([], categories=categories) tm.assert_index_equal(result.categories, Index(categories)) tm.assert_numpy_array_equal(result.codes, np.array([], dtype="int8")) assert not result.ordered