Skip to content

Commit 54f5395

Browse files
committed
update to use can_hold_element instead of naive exact dtype matching
1 parent 9be575a commit 54f5395

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

pandas/core/generic.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@
109109
)
110110

111111
from pandas.core.dtypes.astype import astype_is_view
112+
from pandas.core.dtypes.cast import can_hold_element
112113
from pandas.core.dtypes.common import (
113114
ensure_object,
114115
ensure_platform_int,
@@ -7120,17 +7121,21 @@ def fillna(
71207121
result = self if inplace else self.copy(deep=False)
71217122
if axis == 1:
71227123
# Check that all columns in result have the same dtype
7123-
# otherwise don't bother with ffill and losing accurate dtypes
7124-
dtypes = [result[col].dtype for col in result.columns]
7125-
if len(set(dtypes)) > 1:
7124+
# otherwise don't bother with fillna and losing accurate dtypes
7125+
unique_dtypes = self.dtypes.unique()
7126+
if len(unique_dtypes) > 1:
71267127
raise ValueError(
71277128
"All columns must have the same dtype, but got dtypes: "
7128-
f"{dict(zip(result.columns, dtypes))}"
7129+
f"{list(unique_dtypes)}"
71297130
)
7130-
if (value_dtype := np.asarray(value).dtype) != dtypes[0]:
7131+
# Use the first column, which we have already validated has the
7132+
# same dtypes as the other columns.
7133+
if not can_hold_element(result.iloc[:, 0], value):
7134+
value_dtype = np.asarray(value).dtype
7135+
frame_dtype = unique_dtypes.item()
71317136
raise ValueError(
71327137
"Dtype mismatch for value "
7133-
f"(value.dtype={value_dtype} vs {dtypes[0]})"
7138+
f"(value.dtype={value_dtype} vs {frame_dtype})"
71347139
)
71357140
result = result.T.fillna(value=value).T
71367141
else:

0 commit comments

Comments
 (0)