Skip to content

Commit 77d5ea0

Browse files
nikoskaragiannakisjreback
authored andcommitted
Fix Series construction with dtype=str (#20401)
1 parent 8588960 commit 77d5ea0

File tree

3 files changed

+11
-4
lines changed

3 files changed

+11
-4
lines changed

doc/source/whatsnew/v0.23.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -1149,6 +1149,7 @@ Reshaping
11491149
- Bug in :class:`Series` constructor with ``Categorical`` where a ```ValueError`` is not raised when an index of different length is given (:issue:`19342`)
11501150
- Bug in :meth:`DataFrame.astype` where column metadata is lost when converting to categorical or a dictionary of dtypes (:issue:`19920`)
11511151
- Bug in :func:`cut` and :func:`qcut` where timezone information was dropped (:issue:`19872`)
1152+
- Bug in :class:`Series` constructor with a ``dtype=str``, previously raised in some cases (:issue:`19853`)
11521153

11531154
Other
11541155
^^^^^

pandas/core/series.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -4156,9 +4156,10 @@ def _try_cast(arr, take_fast_path):
41564156
if issubclass(subarr.dtype.type, compat.string_types):
41574157
# GH 16605
41584158
# If not empty convert the data to dtype
4159-
if not isna(data).all():
4160-
data = np.array(data, dtype=dtype, copy=False)
4161-
4162-
subarr = np.array(data, dtype=object, copy=copy)
4159+
# GH 19853: If data is a scalar, subarr has already the result
4160+
if not is_scalar(data):
4161+
if not np.all(isna(data)):
4162+
data = np.array(data, dtype=dtype, copy=False)
4163+
subarr = np.array(data, dtype=object, copy=copy)
41634164

41644165
return subarr

pandas/tests/series/test_constructors.py

+5
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,11 @@ def test_constructor_empty(self, input_class):
110110
empty2 = Series(input_class(), index=lrange(10), dtype='float64')
111111
assert_series_equal(empty, empty2)
112112

113+
# GH 19853 : with empty string, index and dtype str
114+
empty = Series('', dtype=str, index=range(3))
115+
empty2 = Series('', index=range(3))
116+
assert_series_equal(empty, empty2)
117+
113118
@pytest.mark.parametrize('input_arg', [np.nan, float('nan')])
114119
def test_constructor_nan(self, input_arg):
115120
empty = Series(dtype='float64', index=lrange(10))

0 commit comments

Comments
 (0)