Skip to content

Commit d78b8ce

Browse files
committed
Series.round: only coerce object dtype when pd.NA present; preserve legacy TypeError otherwise (GH#61712)
1 parent 4c5e204 commit d78b8ce

File tree

1 file changed

+15
-7
lines changed

1 file changed

+15
-7
lines changed

pandas/core/series.py

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2516,13 +2516,21 @@ def round(self, decimals: int = 0, *args, **kwargs) -> Series:
25162516
"""
25172517
nv.validate_round(args, kwargs)
25182518
if self.dtype == "object":
2519-
# Try to safely cast to a numeric nullable dtype when
2520-
# values are numbers or pd.NA.
2521-
try:
2522-
converted = self.astype("Float64")
2523-
return converted.round(decimals)
2524-
except Exception as err:
2525-
raise TypeError("Expected numeric dtype, got object instead.") from err
2519+
# If the object-dtype Series contains pd.NA and is otherwise numeric,
2520+
# cast to nullable Float64 and round. Otherwise, fall back to the
2521+
# existing implementation to preserve prior behavior (incl. errors).
2522+
has_pd_na = self.isna().any()
2523+
if has_pd_na:
2524+
try:
2525+
converted = self.astype("Float64")
2526+
except Exception as err:
2527+
raise TypeError(
2528+
"Expected numeric dtype, got object instead."
2529+
) from err
2530+
else:
2531+
return converted.round(decimals)
2532+
2533+
raise TypeError("Expected numeric dtype, got object instead.")
25262534
new_mgr = self._mgr.round(decimals=decimals)
25272535
return self._constructor_from_mgr(new_mgr, axes=new_mgr.axes).__finalize__(
25282536
self, method="round"

0 commit comments

Comments
 (0)