Skip to content

Commit a5670f2

Browse files
drewfustinjreback
authored andcommitted
BUG: Allow dtype='category' for Series with Categorical
closes pandas-dev#12636 closes pandas-dev#12574
1 parent f7faee0 commit a5670f2

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

doc/source/whatsnew/v0.18.1.txt

+2
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ Bug Fixes
8989
~~~~~~~~~
9090

9191
- Bug in ``Period`` and ``PeriodIndex`` creation raises ``KeyError`` if ``freq="Minute"`` is specified. Note that "Minute" freq is deprecated in v0.17.0, and recommended to use ``freq="T"`` instead (:issue:`11854`)
92+
- Bug in ``Series`` construction with ``Categorical`` and ``dtype='category'`` is specified (:issue:`12574`)
9293

9394

9495

@@ -129,4 +130,5 @@ Bug Fixes
129130

130131

131132

133+
132134
- Bug in ``pivot_table`` when ``margins=True`` and ``dropna=True`` where nulls still contributed to margin count (:issue:`12577`)

pandas/core/series.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -195,9 +195,12 @@ def __init__(self, data=None, index=None, dtype=None, name=None,
195195
else:
196196
data = data.reindex(index, copy=copy)
197197
elif isinstance(data, Categorical):
198-
if dtype is not None:
198+
# GH12574: Allow dtype=category only, otherwise error
199+
if ((dtype is not None) and
200+
not is_categorical_dtype(dtype)):
199201
raise ValueError("cannot specify a dtype with a "
200-
"Categorical")
202+
"Categorical unless "
203+
"dtype='category'")
201204
elif (isinstance(data, types.GeneratorType) or
202205
(compat.PY3 and isinstance(data, map))):
203206
data = list(data)

pandas/tests/series/test_constructors.py

+11
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,17 @@ def test_constructor_categorical(self):
139139
res = Series(cat)
140140
self.assertTrue(res.values.equals(cat))
141141

142+
# GH12574
143+
self.assertRaises(
144+
ValueError, lambda: Series(pd.Categorical([1, 2, 3]),
145+
dtype='int64'))
146+
cat = Series(pd.Categorical([1, 2, 3]), dtype='category')
147+
self.assertTrue(com.is_categorical_dtype(cat))
148+
self.assertTrue(com.is_categorical_dtype(cat.dtype))
149+
s = Series([1, 2, 3], dtype='category')
150+
self.assertTrue(com.is_categorical_dtype(s))
151+
self.assertTrue(com.is_categorical_dtype(s.dtype))
152+
142153
def test_constructor_maskedarray(self):
143154
data = ma.masked_all((3, ), dtype=float)
144155
result = Series(data)

0 commit comments

Comments
 (0)