Skip to content

Commit dae1c35

Browse files
committed
BUG: Convert data elements when dtype=str in Series constructor with int/float list
1 parent fe900cb commit dae1c35

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

doc/source/whatsnew/v0.22.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,7 @@ Conversion
265265
- Fixed a bug where ``FY5253`` date offsets could incorrectly raise an ``AssertionError`` in arithmetic operatons (:issue:`14774`)
266266
- 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`)
267267
- Bug in :meth:`Series.astype` and ``Categorical.astype()`` where an existing categorical data does not get updated (:issue:`10696`, :issue:`18593`)
268+
- Bug in :class:`Series` constructor with an int or float list where specifying ``dtype=str``, ``dtype='str'`` or ``dtype='U'`` failed to convert the data elements to strings (:issue:`16605`)
268269

269270

270271
Indexing

pandas/core/series.py

+5
Original file line numberDiff line numberDiff line change
@@ -3272,6 +3272,11 @@ def _try_cast(arr, take_fast_path):
32723272
# This is to prevent mixed-type Series getting all casted to
32733273
# NumPy string type, e.g. NaN --> '-1#IND'.
32743274
if issubclass(subarr.dtype.type, compat.string_types):
3275+
# GH 16605
3276+
# If not empty convert the data to dtype
3277+
if not isna(data).all():
3278+
data = np.array(data, dtype=dtype)
3279+
32753280
subarr = np.array(data, dtype=object, copy=copy)
32763281

32773282
return subarr

pandas/tests/series/test_constructors.py

+16
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,22 @@ def test_constructor_list_like(self):
142142
result = Series(obj, index=[0, 1, 2])
143143
assert_series_equal(result, expected)
144144

145+
@pytest.mark.parametrize('input_vals, dtype, expected', [
146+
([1, 2, 3], 'str', ['1', '2', '3']),
147+
([1, 2, 3], str, ['1', '2', '3']),
148+
([1, 2, 3], 'U', ['1', '2', '3']),
149+
([1.0, 2.0, 3.0], 'str', ['1.0', '2.0', '3.0']),
150+
([1.0, 2.0, 3.0], str, ['1.0', '2.0', '3.0']),
151+
([1.0, 2.0, 3.0], 'U', ['1.0', '2.0', '3.0'])
152+
])
153+
def test_constructor_list_str(self, input_vals, dtype, expected):
154+
# GH 16605
155+
# Ensure that data elements are converted to strings when
156+
# dtype is str, 'str', or 'U'
157+
158+
result = Series(input_vals, dtype=dtype)
159+
assert_series_equal(result, Series(expected))
160+
145161
def test_constructor_generator(self):
146162
gen = (i for i in range(10))
147163

0 commit comments

Comments
 (0)