|
109 | 109 | )
|
110 | 110 |
|
111 | 111 | from pandas.core.dtypes.astype import astype_is_view
|
| 112 | +from pandas.core.dtypes.cast import can_hold_element |
112 | 113 | from pandas.core.dtypes.common import (
|
113 | 114 | ensure_object,
|
114 | 115 | ensure_platform_int,
|
@@ -7120,17 +7121,21 @@ def fillna(
|
7120 | 7121 | result = self if inplace else self.copy(deep=False)
|
7121 | 7122 | if axis == 1:
|
7122 | 7123 | # 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: |
7126 | 7127 | raise ValueError(
|
7127 | 7128 | "All columns must have the same dtype, but got dtypes: "
|
7128 |
| - f"{dict(zip(result.columns, dtypes))}" |
| 7129 | + f"{list(unique_dtypes)}" |
7129 | 7130 | )
|
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() |
7131 | 7136 | raise ValueError(
|
7132 | 7137 | "Dtype mismatch for value "
|
7133 |
| - f"(value.dtype={value_dtype} vs {dtypes[0]})" |
| 7138 | + f"(value.dtype={value_dtype} vs {frame_dtype})" |
7134 | 7139 | )
|
7135 | 7140 | result = result.T.fillna(value=value).T
|
7136 | 7141 | else:
|
|
0 commit comments