Skip to content

PERF: reindex default fill_value dtype #57272

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Feb 9, 2024
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
^^^^^^^
Expand Down
6 changes: 5 additions & 1 deletion pandas/core/internals/managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])

Expand Down
6 changes: 6 additions & 0 deletions pandas/tests/frame/methods/test_reindex.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)))

Expand Down