Skip to content

Commit be4dbf8

Browse files
jbrockmendelluckyvs1
authored andcommitted
BUG: disallow scalar in CategoricalIndex construtor (pandas-dev#38614)
1 parent 4796e52 commit be4dbf8

File tree

4 files changed

+9
-8
lines changed

4 files changed

+9
-8
lines changed

doc/source/whatsnew/v1.3.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ Bug fixes
171171

172172
Categorical
173173
^^^^^^^^^^^
174-
174+
- Bug in :class:`CategoricalIndex` incorrectly failing to raise ``TypeError`` when scalar data is passed (:issue:`38614`)
175175
- Bug in ``CategoricalIndex.reindex`` failed when ``Index`` passed with elements all in category (:issue:`28690`)
176176
- Bug where construcing a :class:`Categorical` from an object-dtype array of ``date`` objects did not round-trip correctly with ``astype`` (:issue:`38552`)
177177

pandas/core/indexes/category.py

+1-5
Original file line numberDiff line numberDiff line change
@@ -186,11 +186,7 @@ def __new__(
186186
name = maybe_extract_name(name, data, cls)
187187

188188
if is_scalar(data):
189-
# don't allow scalars
190-
# if data is None, then categories must be provided
191-
if data is not None or categories is None:
192-
raise cls._scalar_data_error(data)
193-
data = []
189+
raise cls._scalar_data_error(data)
194190

195191
data = Categorical(
196192
data, categories=categories, ordered=ordered, dtype=dtype, copy=copy

pandas/tests/indexes/categorical/test_category.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ def test_insert(self):
9191
tm.assert_index_equal(result, expected, exact=True)
9292

9393
# test empty
94-
result = CategoricalIndex(categories=categories).insert(0, "a")
94+
result = CategoricalIndex([], categories=categories).insert(0, "a")
9595
expected = CategoricalIndex(["a"], categories=categories)
9696
tm.assert_index_equal(result, expected, exact=True)
9797

pandas/tests/indexes/categorical/test_constructors.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,11 @@
66

77

88
class TestCategoricalIndexConstructors:
9+
def test_construction_disallows_scalar(self):
10+
msg = "must be called with a collection of some kind"
11+
with pytest.raises(TypeError, match=msg):
12+
CategoricalIndex(categories=list("abcd"), ordered=False)
13+
914
def test_construction(self):
1015

1116
ci = CategoricalIndex(list("aabbca"), categories=list("abcd"), ordered=False)
@@ -20,7 +25,7 @@ def test_construction(self):
2025
assert not result.ordered
2126

2227
# empty
23-
result = CategoricalIndex(categories=categories)
28+
result = CategoricalIndex([], categories=categories)
2429
tm.assert_index_equal(result.categories, Index(categories))
2530
tm.assert_numpy_array_equal(result.codes, np.array([], dtype="int8"))
2631
assert not result.ordered

0 commit comments

Comments
 (0)