diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index 81c3f88f7e8ad..53d2025448640 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -161,7 +161,7 @@ Numeric Conversion ^^^^^^^^^^ - Bug in :meth:`Series.astype` might modify read-only array inplace when casting to a string dtype (:issue:`57212`) -- +- Bug in :meth:`Series.reindex` not maintaining ``float32`` type when a ``reindex`` introduces a missing value (:issue:`45857`) Strings ^^^^^^^ diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index cda5575a2b04e..615bcd4602058 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -1050,8 +1050,12 @@ def _make_na_block( nb = NumpyBlock(vals, placement, ndim=2) return nb - if fill_value is None: + if fill_value is None or fill_value is np.nan: fill_value = np.nan + # GH45857 avoid unnecessary upcasting + dtype = interleaved_dtype([blk.dtype for blk in self.blocks]) + if dtype is not None and np.issubdtype(dtype.type, np.floating): + fill_value = dtype.type(fill_value) shape = (len(placement), self.shape[1]) diff --git a/pandas/tests/frame/methods/test_reindex.py b/pandas/tests/frame/methods/test_reindex.py index 76d80e87bdeb5..229ca6e6b683a 100644 --- a/pandas/tests/frame/methods/test_reindex.py +++ b/pandas/tests/frame/methods/test_reindex.py @@ -1018,6 +1018,12 @@ def test_reindex_with_nans(self): expected = df.iloc[[1]] tm.assert_frame_equal(result, expected) + def test_reindex_without_upcasting(self): + # GH45857 + df = DataFrame(np.zeros((10, 10), dtype=np.float32)) + result = df.reindex(columns=np.arange(5, 15)) + assert result.dtypes.eq(np.float32).all() + def test_reindex_multi(self): df = DataFrame(np.random.default_rng(2).standard_normal((3, 3)))