diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index 834477f2aa46a..2d7d848146d62 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -752,6 +752,7 @@ Conversion - Bug in :meth:`Series.astype` might modify read-only array inplace when casting to a string dtype (:issue:`57212`) - Bug in :meth:`Series.convert_dtypes` and :meth:`DataFrame.convert_dtypes` removing timezone information for objects with :class:`ArrowDtype` (:issue:`60237`) - Bug in :meth:`Series.reindex` not maintaining ``float32`` type when a ``reindex`` introduces a missing value (:issue:`45857`) +- Bug in :meth:`_array_ops._maybe_prepare_scalar_for_op` not maintaining ``float32`` type when converting NumPy floating scalars (:issue:`61951`) Strings ^^^^^^^ diff --git a/pandas/core/ops/array_ops.py b/pandas/core/ops/array_ops.py index 3a466b6fc7fc8..d1e211cd991be 100644 --- a/pandas/core/ops/array_ops.py +++ b/pandas/core/ops/array_ops.py @@ -573,7 +573,7 @@ def maybe_prepare_scalar_for_op(obj, shape: Shape): return int(obj) elif isinstance(obj, np.floating): - return float(obj) + return np.dtype(obj.dtype).type(obj) return obj diff --git a/pandas/tests/series/methods/test_convert_dtypes.py b/pandas/tests/series/methods/test_convert_dtypes.py index 324e03894e92c..b89255a0ae8ee 100644 --- a/pandas/tests/series/methods/test_convert_dtypes.py +++ b/pandas/tests/series/methods/test_convert_dtypes.py @@ -318,3 +318,9 @@ def test_convert_dtype_pyarrow_timezone_preserve(self): result = ser.convert_dtypes(dtype_backend="pyarrow") expected = ser.copy() tm.assert_series_equal(result, expected) + + def test_float32_series_addition_preserves_dtype(self): + # GH#61951 + ser_a = pd.Series(np.zeros(1000000), dtype="float32") + np.float32(1) + ser_b = pd.Series(np.zeros(1000001), dtype="float32") + np.float32(1) + assert all(dtype == np.float32 for dtype in (ser_a.dtype, ser_b.dtype))