diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 932618ba1df21d..62748fcc99cd49 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -690,6 +690,7 @@ Categorical - 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`) - Bug in :meth:`Series.astype` and ``Categorical.astype()`` where an existing categorical data does not get updated (:issue:`10696`, :issue:`18593`) - Bug in :class:`Index` constructor with ``dtype=CategoricalDtype(...)`` where ``categories`` and ``ordered`` are not maintained (issue:`19032`) +- Bug in :class:`Series` constructor with ``Categorical`` where an error is not raised when an index of incorrect length is given (:issue:`19342`) Datetimelike ^^^^^^^^^^^^ diff --git a/pandas/core/series.py b/pandas/core/series.py index 655eaa5373f5af..db8beff84379cc 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -210,6 +210,11 @@ def __init__(self, data=None, index=None, dtype=None, name=None, raise ValueError("cannot specify a dtype with a " "Categorical unless " "dtype='category'") + if index is not None and len(index) != len(data): + raise ValueError('Length of passed values is {val}, ' + 'index implies {ind}' + .format(val=len(data), ind=len(index))) + elif (isinstance(data, types.GeneratorType) or (compat.PY3 and isinstance(data, map))): data = list(data) diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 33737387edffa4..47590a713724fc 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -393,6 +393,16 @@ def test_constructor_default_index(self): s = Series([0, 1, 2]) tm.assert_index_equal(s.index, pd.Index(np.arange(3))) + @pytest.mark.parametrize('input', [[1, 2, 3], + (1, 2, 3), + list(range(3)), + pd.Categorical(['a', 'b', 'a']), + (i for i in range(3)), + map(lambda x: x, range(3))]) + def test_constructor_index_mismatch(self, input): + # GH 19342 + pytest.raises(ValueError, Series, input, index=np.arange(4)) + def test_constructor_corner(self): df = tm.makeTimeDataFrame() objs = [df, df]