Skip to content

Commit 1434b63

Browse files
committed
BUG: Fix Series constructor for Categorical with index
Fixes Series constructor so that ValueError is raised when a Categorical and index of incorrect length are given.
1 parent 11de131 commit 1434b63

File tree

3 files changed

+16
-0
lines changed

3 files changed

+16
-0
lines changed

doc/source/whatsnew/v0.23.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -690,6 +690,7 @@ Categorical
690690
- Bug in :meth:`Index.astype` with a categorical dtype where the resultant index is not converted to a :class:`CategoricalIndex` for all types of index (:issue:`18630`)
691691
- Bug in :meth:`Series.astype` and ``Categorical.astype()`` where an existing categorical data does not get updated (:issue:`10696`, :issue:`18593`)
692692
- Bug in :class:`Index` constructor with ``dtype=CategoricalDtype(...)`` where ``categories`` and ``ordered`` are not maintained (issue:`19032`)
693+
- Bug in :class:`Series` constructor with ``Categorical`` where an error is not raised when an index of incorrect length is given (:issue:`19342`)
693694

694695
Datetimelike
695696
^^^^^^^^^^^^

pandas/core/series.py

+5
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,11 @@ def __init__(self, data=None, index=None, dtype=None, name=None,
210210
raise ValueError("cannot specify a dtype with a "
211211
"Categorical unless "
212212
"dtype='category'")
213+
if index is not None and len(index) != len(data):
214+
raise ValueError('Length of passed values is {val}, '
215+
'index implies {ind}'
216+
.format(val=len(data), ind=len(index)))
217+
213218
elif (isinstance(data, types.GeneratorType) or
214219
(compat.PY3 and isinstance(data, map))):
215220
data = list(data)

pandas/tests/series/test_constructors.py

+10
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,16 @@ def test_constructor_default_index(self):
393393
s = Series([0, 1, 2])
394394
tm.assert_index_equal(s.index, pd.Index(np.arange(3)))
395395

396+
@pytest.mark.parametrize('input', [[1, 2, 3],
397+
(1, 2, 3),
398+
list(range(3)),
399+
pd.Categorical(['a', 'b', 'a']),
400+
(i for i in range(3)),
401+
map(lambda x: x, range(3))])
402+
def test_constructor_index_mismatch(self, input):
403+
# GH 19342
404+
pytest.raises(ValueError, Series, input, index=np.arange(4))
405+
396406
def test_constructor_corner(self):
397407
df = tm.makeTimeDataFrame()
398408
objs = [df, df]

0 commit comments

Comments
 (0)