Skip to content

Commit cb0fcae

Browse files
committed
PERF: maybe_promote
1 parent 9935690 commit cb0fcae

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

pandas/core/dtypes/cast.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
from pandas._libs.missing import (
2424
NA,
2525
NAType,
26+
checknull,
2627
)
2728
from pandas._libs.tslibs import (
2829
NaT,
@@ -556,6 +557,13 @@ def ensure_dtype_can_hold_na(dtype: DtypeObj) -> DtypeObj:
556557
return dtype
557558

558559

560+
_canonical_nans = {
561+
np.datetime64: np.datetime64("NaT", "ns"),
562+
np.timedelta64: np.timedelta64("NaT", "ns"),
563+
type(np.nan): np.nan,
564+
}
565+
566+
559567
def maybe_promote(dtype: np.dtype, fill_value=np.nan):
560568
"""
561569
Find the minimal dtype that can hold both the given dtype and fill_value.
@@ -577,6 +585,11 @@ def maybe_promote(dtype: np.dtype, fill_value=np.nan):
577585
ValueError
578586
If fill_value is a non-scalar and dtype is not object.
579587
"""
588+
if checknull(fill_value):
589+
# https://github.com/pandas-dev/pandas/pull/39692#issuecomment-1441051740
590+
# avoid cache misses with NaN/NaT values that are not singletons
591+
fill_value = _canonical_nans.get(type(fill_value), fill_value)
592+
580593
# for performance, we are using a cached version of the actual implementation
581594
# of the function in _maybe_promote. However, this doesn't always work (in case
582595
# of non-hashable arguments), so we fallback to the actual implementation if needed

0 commit comments

Comments
 (0)