diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 929dfa5c12078..5f1c9c1889240 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1811,8 +1811,17 @@ def maybe_cast_to_integer_array( # doesn't handle `uint64` correctly. arr = np.asarray(arr) - if is_unsigned_integer_dtype(dtype) and (arr < 0).any(): - raise OverflowError("Trying to coerce negative values to unsigned integers") + if is_unsigned_integer_dtype(dtype): + try: + if (arr < 0).any(): + raise OverflowError( + "Trying to coerce negative values to unsigned integers" + ) + except TypeError: + if (casted < 0).any(): + raise OverflowError( + "Trying to coerce negative values to unsigned integers" + ) if is_float_dtype(arr.dtype): if not np.isfinite(arr).all(): @@ -1823,7 +1832,7 @@ def maybe_cast_to_integer_array( if is_object_dtype(arr.dtype): raise ValueError("Trying to coerce float values to integers") - if casted.dtype < arr.dtype: + if casted.dtype < arr.dtype or is_string_dtype(arr.dtype): # GH#41734 e.g. [1, 200, 923442] and dtype="int8" -> overflows warnings.warn( f"Values are too large to be losslessly cast to {dtype}. " diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 3b7ae28be68fa..b33e3d88b7748 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -1895,6 +1895,20 @@ def test_constructor_bool_dtype_missing_values(self): expected = Series(True, index=[0], dtype="bool") tm.assert_series_equal(result, expected) + def test_constructor_int64_dtype(self, any_int_dtype): + # GH-44923 + result = Series(["0", "1", "2"], dtype=any_int_dtype) + expected = Series([0, 1, 2], dtype=any_int_dtype) + tm.assert_series_equal(result, expected) + + def test_constructor_float64_dtype(self, any_float_dtype): + # GH-44923 + if any_float_dtype in ["Float32", "Float64"]: + pytest.xfail(reason="Cannot be casted to FloatDtype Series") + result = Series(["-1", "0", "1", "2"], dtype=any_float_dtype) + expected = Series([-1.0, 0.0, 1.0, 2.0], dtype=any_float_dtype) + tm.assert_series_equal(result, expected) + @pytest.mark.filterwarnings( "ignore:elementwise comparison failed:DeprecationWarning" )