Skip to content

Commit ffd643a

Browse files
committed
BUG: Series.round with pd.NA no longer raises; coerce object+NA to nullable float and round; add test (#61712)
1 parent 4257ad6 commit ffd643a

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

pandas/core/series.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2516,7 +2516,12 @@ def round(self, decimals: int = 0, *args, **kwargs) -> Series:
25162516
"""
25172517
nv.validate_round(args, kwargs)
25182518
if self.dtype == "object":
2519-
raise TypeError("Expected numeric dtype, got object instead.")
2519+
# Try to safely cast to numeric type (like float) if values are pd.NA or numbers
2520+
try:
2521+
converted = self.astype("Float64")
2522+
return converted.round(decimals)
2523+
except Exception:
2524+
raise TypeError("Expected numeric dtype, got object instead.")
25202525
new_mgr = self._mgr.round(decimals=decimals)
25212526
return self._constructor_from_mgr(new_mgr, axes=new_mgr.axes).__finalize__(
25222527
self, method="round"

pandas/tests/series/methods/test_round.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,3 +79,11 @@ def test_round_dtype_object(self):
7979
msg = "Expected numeric dtype, got object instead."
8080
with pytest.raises(TypeError, match=msg):
8181
ser.round()
82+
83+
def test_round_with_pd_na(self):
84+
import pandas as pd
85+
import numpy as np
86+
s = pd.Series([0.5, pd.NA], dtype="object")
87+
result = s.round(0)
88+
expected = pd.Series([0.0, pd.NA], dtype="Float64")
89+
pd.testing.assert_series_equal(result, expected)

0 commit comments

Comments
 (0)