Skip to content

Commit 1276dad

Browse files
committed
BUG: fix Series constructor for scalar and Categorical dtype
Categories and ordering of the resulting Series were not the same as those of the passed Categorical dtype
1 parent 2fdf1e2 commit 1276dad

File tree

3 files changed

+17
-2
lines changed

3 files changed

+17
-2
lines changed

doc/source/whatsnew/v0.23.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -691,6 +691,7 @@ Categorical
691691
- 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`)
692692
- Bug in :meth:`Series.astype` and ``Categorical.astype()`` where an existing categorical data does not get updated (:issue:`10696`, :issue:`18593`)
693693
- Bug in :class:`Index` constructor with ``dtype=CategoricalDtype(...)`` where ``categories`` and ``ordered`` are not maintained (issue:`19032`)
694+
- Bug in :class:`Series` constructor with scalar and ``dtype=CategoricalDtype(...)`` where ``categories`` and ``ordered`` are not maintained (issue:`19565`)
694695

695696
Datetimelike
696697
^^^^^^^^^^^^

pandas/core/dtypes/cast.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1178,7 +1178,8 @@ def construct_1d_arraylike_from_scalar(value, length, dtype):
11781178
subarr = DatetimeIndex([value] * length, dtype=dtype)
11791179
elif is_categorical_dtype(dtype):
11801180
from pandas import Categorical
1181-
subarr = Categorical([value] * length)
1181+
subarr = Categorical([value] * length, dtype.categories,
1182+
ordered=dtype.ordered)
11821183
else:
11831184
if not isinstance(dtype, (np.dtype, type(np.dtype))):
11841185
dtype = dtype.dtype

pandas/tests/dtypes/test_cast.py

+14-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@
2222
maybe_convert_string_to_object,
2323
maybe_convert_scalar,
2424
find_common_type,
25-
construct_1d_object_array_from_listlike)
25+
construct_1d_object_array_from_listlike,
26+
construct_1d_arraylike_from_scalar)
2627
from pandas.core.dtypes.dtypes import (
2728
CategoricalDtype,
2829
DatetimeTZDtype,
@@ -422,3 +423,15 @@ def test_cast_1d_array(self, datum1, datum2):
422423
@pytest.mark.parametrize('val', [1, 2., None])
423424
def test_cast_1d_array_invalid_scalar(self, val):
424425
pytest.raises(TypeError, construct_1d_object_array_from_listlike, val)
426+
427+
def test_cast_1d_arraylike_from_scalar_categorical(self):
428+
# GH 19565 - Categorical result from scalar did not maintain categories
429+
# and ordering of the passed dtype
430+
cats = ['a', 'b', 'c']
431+
cat_type = CategoricalDtype(categories=cats, ordered=False)
432+
expected = pd.Categorical(['a', 'a'], categories=cats)
433+
result = construct_1d_arraylike_from_scalar('a', len(expected),
434+
cat_type)
435+
tm.assert_categorical_equal(result, expected,
436+
check_category_order=True,
437+
check_dtype=True)

0 commit comments

Comments
 (0)