Skip to content

Commit

Permalink
BUG: disallow scalar in CategoricalIndex construtor (pandas-dev#38614)
Browse files Browse the repository at this point in the history
  • Loading branch information
jbrockmendel authored and luckyvs1 committed Jan 20, 2021
1 parent 4796e52 commit be4dbf8
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 8 deletions.
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,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`)
- Bug where construcing a :class:`Categorical` from an object-dtype array of ``date`` objects did not round-trip correctly with ``astype`` (:issue:`38552`)

Expand Down
6 changes: 1 addition & 5 deletions pandas/core/indexes/category.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/indexes/categorical/test_category.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
7 changes: 6 additions & 1 deletion pandas/tests/indexes/categorical/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down

0 comments on commit be4dbf8

Please sign in to comment.