Skip to content

Commit 1f365aa

Browse files
committed
make sure conversion is not lossy
1 parent eed6176 commit 1f365aa

File tree

2 files changed

+7
-1
lines changed

2 files changed

+7
-1
lines changed

pandas/core/dtypes/cast.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1851,7 +1851,7 @@ def maybe_cast_to_integer_array(
18511851
# doesn't handle `uint64` correctly.
18521852
arr = np.asarray(arr)
18531853

1854-
if np.issubdtype(arr.dtype, str):
1854+
if np.issubdtype(arr.dtype, str) and (casted.astype(str) == arr).all():
18551855
return casted
18561856

18571857
if is_unsigned_integer_dtype(dtype) and (arr < 0).any():

pandas/tests/series/test_constructors.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1886,6 +1886,12 @@ def test_constructor_int64_dtype(self, any_int_dtype):
18861886
expected = Series([0, 1, 2], dtype=any_int_dtype)
18871887
tm.assert_series_equal(result, expected)
18881888

1889+
def test_constructor_raise_on_lossy_conversion_of_strings(self):
1890+
with pytest.raises(
1891+
ValueError, match="values cannot be losslessly cast to int8"
1892+
):
1893+
Series(["128"], dtype="int8")
1894+
18891895
def test_constructor_dtype_timedelta_alternative_construct(self):
18901896
# GH#35465
18911897
result = Series([1000000, 200000, 3000000], dtype="timedelta64[ns]")

0 commit comments

Comments
 (0)