diff --git a/doc/source/whatsnew/v0.18.1.txt b/doc/source/whatsnew/v0.18.1.txt index a3e20879a2f58..f382efa90cbc0 100644 --- a/doc/source/whatsnew/v0.18.1.txt +++ b/doc/source/whatsnew/v0.18.1.txt @@ -93,3 +93,5 @@ Bug Fixes - Bug in ``value_counts`` when ``normalize=True`` and ``dropna=True`` where nulls still contributed to the normalized count (:issue:`12558`) - Bug in ``CategoricalIndex.get_loc`` returns different result from regular ``Index`` (:issue:`12531`) + +- Bug in ``Series`` when Series with Categorical is created with dtype specified (:issue:`12574`) diff --git a/pandas/core/series.py b/pandas/core/series.py index d339a93a3ed9b..649d5dbe8f384 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -195,9 +195,12 @@ def __init__(self, data=None, index=None, dtype=None, name=None, else: data = data.reindex(index, copy=copy) elif isinstance(data, Categorical): - if dtype is not None: + # GH12574: Allow dtype=category only, otherwise error + if ((dtype is not None) and + not is_categorical_dtype(dtype)): raise ValueError("cannot specify a dtype with a " - "Categorical") + "Categorical unless " + "dtype='category'") 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 43e47ae121408..356267630b274 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -139,6 +139,17 @@ def test_constructor_categorical(self): res = Series(cat) self.assertTrue(res.values.equals(cat)) + # GH12574 + self.assertRaises( + ValueError, lambda: Series(pd.Categorical([1, 2, 3]), + dtype='int64')) + cat = Series(pd.Categorical([1, 2, 3]), dtype='category') + self.assertTrue(com.is_categorical_dtype(cat)) + self.assertTrue(com.is_categorical_dtype(cat.dtype)) + s = Series([1, 2, 3], dtype='category') + self.assertTrue(com.is_categorical_dtype(s)) + self.assertTrue(com.is_categorical_dtype(s.dtype)) + def test_constructor_maskedarray(self): data = ma.masked_all((3, ), dtype=float) result = Series(data)