Skip to content

Commit

Permalink
BUG: Fix Series constructor for Categorical with index
Browse files Browse the repository at this point in the history
Fixes Series constructor so that ValueError is raised when a Categorical and index of incorrect length are given.
  • Loading branch information
cbertinato committed Feb 14, 2018
1 parent 11de131 commit 1434b63
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 0 deletions.
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.23.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
^^^^^^^^^^^^
Expand Down
5 changes: 5 additions & 0 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/series/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down

0 comments on commit 1434b63

Please sign in to comment.