Skip to content

BUG: fillna with DataFrame input should preserve dtype when possible #61742

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -748,7 +748,7 @@ Indexing
Missing
^^^^^^^
- Bug in :meth:`DataFrame.fillna` and :meth:`Series.fillna` that would ignore the ``limit`` argument on :class:`.ExtensionArray` dtypes (:issue:`58001`)
-
- Bug in :meth:`DataFrame.fillna` where filling from another ``DataFrame`` of the same dtype could incorrectly cast the result to ``object`` dtype. (:issue:`61568`)

MultiIndex
^^^^^^^^^^
Expand Down
19 changes: 18 additions & 1 deletion pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -7145,7 +7145,24 @@ def fillna(
else:
new_data = self._mgr.fillna(value=value, limit=limit, inplace=inplace)
elif isinstance(value, ABCDataFrame) and self.ndim == 2:
new_data = self.where(self.notna(), value)._mgr
filled_columns = {}
for col in self.columns:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

doing this column-by-column is going to mean a performance hit for non-object cases. i suspect we need to do this at the Block level in order to avoid that

lhs = self[col]
if col in value.columns:
rhs = value[col]
filled = lhs.where(notna(lhs), rhs)

# restore original dtype if fallback to object occurred
if lhs.dtype == rhs.dtype and filled.dtype == object:
try:
filled = filled.astype(lhs.dtype)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

id expect this to be handled by Series.where. is it not?

except Exception:
pass
else:
filled = lhs
filled_columns[col] = filled

new_data = type(self)(filled_columns, index=self.index)._mgr
else:
raise ValueError(f"invalid fill value with a {type(value)}")

Expand Down
19 changes: 19 additions & 0 deletions pandas/tests/frame/methods/test_fillna.py
Original file line number Diff line number Diff line change
Expand Up @@ -795,3 +795,22 @@ def test_fillna_out_of_bounds_datetime():
msg = "Cannot cast 0001-01-01 00:00:00 to unit='ns' without overflow"
with pytest.raises(OutOfBoundsDatetime, match=msg):
df.fillna(Timestamp("0001-01-01"))


def test_fillna_dataframe_preserves_dtypes_mixed_columns():
# GH#61568
empty = DataFrame([[None] * 4] * 4, columns=list("ABCD"), dtype=np.float64)
full = DataFrame(
[
[1.0, 2.0, "3.0", 4.0],
[5.0, 6.0, "7.0", 8.0],
[9.0, 10.0, "11.0", 12.0],
[13.0, 14.0, "15.0", 16.0],
],
columns=list("ABCD"),
)
result = empty.fillna(full)
expected_dtypes = Series(
{"A": "float64", "B": "float64", "C": "object", "D": "float64"}
)
tm.assert_series_equal(result.dtypes, expected_dtypes)
Loading