From 2de8bffe2690c899a82f9ace52303333f46edeb7 Mon Sep 17 00:00:00 2001 From: Nitish Satyavolu Date: Fri, 7 Feb 2025 19:01:19 -0800 Subject: [PATCH 1/2] BUG: Don't ignore errors when casting dtype in Series constructor --- pandas/core/series.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pandas/core/series.py b/pandas/core/series.py index 4fa8b86fa4c16..351622135b31f 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -500,7 +500,7 @@ def __init__( # create/copy the manager if isinstance(data, SingleBlockManager): if dtype is not None: - data = data.astype(dtype=dtype, errors="ignore") + data = data.astype(dtype=dtype) elif copy: data = data.copy() else: From 2ee4774ac3b2fd58e578fa13542860ed36fa4abe Mon Sep 17 00:00:00 2001 From: Nitish Satyavolu Date: Fri, 7 Feb 2025 19:45:24 -0800 Subject: [PATCH 2/2] Add test and whatsnew --- doc/source/whatsnew/v3.0.0.rst | 1 + pandas/tests/series/test_constructors.py | 7 +++++++ 2 files changed, 8 insertions(+) diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index 7ebbfd5bf75be..570faa00e97a8 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -793,6 +793,7 @@ Styler Other ^^^^^ - Bug in :class:`DataFrame` when passing a ``dict`` with a NA scalar and ``columns`` that would always return ``np.nan`` (:issue:`57205`) +- Bug in :class:`Series` ignoring errors when trying to convert :class:`Series` input data to the given ``dtype`` (:issue:`60728`) - Bug in :func:`eval` on :class:`ExtensionArray` on including division ``/`` failed with a ``TypeError``. (:issue:`58748`) - Bug in :func:`eval` where the names of the :class:`Series` were not preserved when using ``engine="numexpr"``. (:issue:`10239`) - Bug in :func:`eval` with ``engine="numexpr"`` returning unexpected result for float division. (:issue:`59736`) diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 69f42b5e42878..a2be698c0ec28 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -90,6 +90,13 @@ def test_unparsable_strings_with_dt64_dtype(self): with pytest.raises(ValueError, match=msg): Series(np.array(vals, dtype=object), dtype="datetime64[ns]") + def test_invalid_dtype_conversion_datetime_to_timedelta(self): + # GH#60728 + vals = Series([NaT, Timestamp(2025, 1, 1)], dtype="datetime64[ns]") + msg = r"^Cannot cast DatetimeArray to dtype timedelta64\[ns\]$" + with pytest.raises(TypeError, match=msg): + Series(vals, dtype="timedelta64[ns]") + @pytest.mark.parametrize( "constructor", [