Skip to content

Commit f878ddc

Browse files
authored
PERF/CLN: float-to-int casting (#31409)
1 parent f6146a5 commit f878ddc

File tree

3 files changed

+6
-11
lines changed

3 files changed

+6
-11
lines changed

pandas/core/arrays/integer.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
from pandas.core.dtypes.missing import isna
2626

2727
from pandas.core import nanops, ops
28+
import pandas.core.common as com
2829
from pandas.core.indexers import check_array_indexer
2930
from pandas.core.ops import invalid_comparison
3031
from pandas.core.ops.common import unpack_zerodim_and_defer
@@ -586,9 +587,8 @@ def _reduce(self, name, skipna=True, **kwargs):
586587
# if we have a preservable numeric op,
587588
# provide coercion back to an integer type if possible
588589
elif name in ["sum", "min", "max", "prod"]:
589-
int_result = int(result)
590-
if int_result == result:
591-
result = int_result
590+
# GH#31409 more performant than casting-then-checking
591+
result = com.cast_scalar_indexer(result)
592592

593593
return result
594594

pandas/core/common.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ def cast_scalar_indexer(val):
156156
outval : scalar
157157
"""
158158
# assumes lib.is_scalar(val)
159-
if lib.is_float(val) and val == int(val):
159+
if lib.is_float(val) and val.is_integer():
160160
return int(val)
161161
return val
162162

pandas/core/indexes/base.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4929,13 +4929,8 @@ def _maybe_cast_indexer(self, key):
49294929
to an int if equivalent.
49304930
"""
49314931

4932-
if is_float(key) and not self.is_floating():
4933-
try:
4934-
ckey = int(key)
4935-
if ckey == key:
4936-
key = ckey
4937-
except (OverflowError, ValueError, TypeError):
4938-
pass
4932+
if not self.is_floating():
4933+
return com.cast_scalar_indexer(key)
49394934
return key
49404935

49414936
def _validate_indexer(self, form: str_t, key, kind: str_t):

0 commit comments

Comments
 (0)