Skip to content

Commit 672fb14

Browse files
rinocjreback
authored andcommitted
BUG: Init categorical series from value
closes #12336 closes #12368
1 parent 596036c commit 672fb14

File tree

3 files changed

+11
-0
lines changed

3 files changed

+11
-0
lines changed

doc/source/whatsnew/v0.18.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -1107,3 +1107,4 @@ Bug Fixes
11071107
- Bug in ``crosstab`` where arguments with non-overlapping indexes would return a ``KeyError`` (:issue:`10291`)
11081108

11091109
- Bug in ``DataFrame.apply`` in which reduction was not being prevented for cases in which ``dtype`` was not a numpy dtype (:issue:`12244`)
1110+
- Bug when initializing categorical series with a scalar value. (:issue:`12336`)

pandas/core/series.py

+2
Original file line numberDiff line numberDiff line change
@@ -2926,6 +2926,8 @@ def create_from_value(value, index, dtype):
29262926

29272927
if is_datetimetz(dtype):
29282928
subarr = DatetimeIndex([value] * len(index), dtype=dtype)
2929+
elif is_categorical_dtype(dtype):
2930+
subarr = Categorical([value] * len(index))
29292931
else:
29302932
if not isinstance(dtype, (np.dtype, type(np.dtype))):
29312933
dtype = dtype.dtype

pandas/tests/series/test_constructors.py

+8
Original file line numberDiff line numberDiff line change
@@ -635,6 +635,14 @@ def test_fromValue(self):
635635
self.assertEqual(dates.dtype, 'M8[ns]')
636636
self.assertEqual(len(dates), len(self.ts))
637637

638+
# GH12336
639+
# Test construction of categorical series from value
640+
categorical = Series(0, index=self.ts.index, dtype="category")
641+
expected = Series(0, index=self.ts.index).astype("category")
642+
self.assertEqual(categorical.dtype, 'category')
643+
self.assertEqual(len(categorical), len(self.ts))
644+
tm.assert_series_equal(categorical, expected)
645+
638646
def test_constructor_dtype_timedelta64(self):
639647

640648
# basic

0 commit comments

Comments
 (0)