Skip to content

Commit 3bc499d

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 different length are given.
1 parent 11de131 commit 3bc499d

File tree

3 files changed

+35
-0
lines changed

3 files changed

+35
-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 different 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

+29
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
from datetime import datetime, timedelta
77
from collections import OrderedDict
8+
import types
89

910
from numpy import nan
1011
import numpy as np
@@ -22,6 +23,7 @@
2223
from pandas._libs import lib
2324
from pandas._libs.tslib import iNaT
2425

26+
from pandas import compat
2527
from pandas.compat import lrange, range, zip, long
2628
from pandas.util.testing import assert_series_equal
2729
import pandas.util.testing as tm
@@ -393,6 +395,33 @@ def test_constructor_default_index(self):
393395
s = Series([0, 1, 2])
394396
tm.assert_index_equal(s.index, pd.Index(np.arange(3)))
395397

398+
@pytest.mark.parametrize('input', [[1, 2, 3],
399+
(1, 2, 3),
400+
list(range(3)),
401+
pd.Categorical(['a', 'b', 'a']),
402+
(i for i in range(3)),
403+
map(lambda x: x, range(3))])
404+
def test_constructor_index_mismatch(self, input):
405+
# GH 19342
406+
# test that construction of a Series with an index of different length
407+
# raises an error
408+
idx = np.arange(4)
409+
410+
if compat.PY2:
411+
typs = types.GeneratorType
412+
else:
413+
typs = (map, types.GeneratorType)
414+
415+
if isinstance(input, typs):
416+
input_len = len(list(input))
417+
else:
418+
input_len = len(input)
419+
420+
msg = ('Length of passed values is {val}, index implies {ind}'
421+
.format(val=input_len, ind=len(idx)))
422+
with pytest.raises(ValueError, message=msg):
423+
Series(input, index=idx)
424+
396425
def test_constructor_corner(self):
397426
df = tm.makeTimeDataFrame()
398427
objs = [df, df]

0 commit comments

Comments
 (0)