Skip to content

Commit 4b52a2a

Browse files
committed
make sure conversion is not lossy
1 parent 2d8d313 commit 4b52a2a

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

pandas/core/dtypes/cast.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1851,6 +1851,9 @@ 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) and (casted.astype(str) == arr).all():
1855+
return casted
1856+
18541857
if is_unsigned_integer_dtype(dtype) and (arr < 0).any():
18551858
raise OverflowError("Trying to coerce negative values to unsigned integers")
18561859

pandas/tests/series/test_constructors.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1880,6 +1880,18 @@ def test_constructor_bool_dtype_missing_values(self):
18801880
expected = Series(True, index=[0], dtype="bool")
18811881
tm.assert_series_equal(result, expected)
18821882

1883+
def test_constructor_int64_dtype(self, any_int_dtype):
1884+
# GH#44923
1885+
result = Series(["0", "1", "2"], dtype=any_int_dtype)
1886+
expected = Series([0, 1, 2], dtype=any_int_dtype)
1887+
tm.assert_series_equal(result, expected)
1888+
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+
18831895
def test_constructor_dtype_timedelta_alternative_construct(self):
18841896
# GH#35465
18851897
result = Series([1000000, 200000, 3000000], dtype="timedelta64[ns]")

0 commit comments

Comments
 (0)