From a3a932be3fae4075f6087fc40a6af5ad6cf3189b Mon Sep 17 00:00:00 2001 From: jbrockmendel Date: Sat, 6 Jul 2019 14:15:35 -0700 Subject: [PATCH 1/2] Avoid wrapping pd.Index --- pandas/core/ops/__init__.py | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index 4692ec45df0ad..eccfd02e50f00 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -43,6 +43,7 @@ ABCSeries, ABCSparseArray, ABCSparseSeries, + ABCTimedeltaArray, ) from pandas.core.dtypes.missing import isna, notna @@ -1716,10 +1717,32 @@ def wrapper(left, right): # Note: we cannot use dispatch_to_index_op because # that may incorrectly raise TypeError when we # should get NullFrequencyError - result = op(pd.Index(left), right) - return construct_result( - left, result, index=left.index, name=res_name, dtype=result.dtype - ) + orig_right = right + if is_scalar(right): + # broadcast and wrap in a TimedeltaIndex + # TODO: possible perf improvement by using NaTD scalar + # here (GH#24983) + assert np.isnat(right) + right = np.broadcast_to(right, left.shape) + right = pd.TimedeltaIndex(right) + + assert isinstance(right, (pd.TimedeltaIndex, ABCTimedeltaArray, ABCSeries)) + try: + result = op(left._values, right) + except NullFrequencyError: + if orig_right is not right: + # i.e. scalar timedelta64('NaT') + # We get a NullFrequencyError because we broadcast to + # TimedeltaIndex, but this should be TypeError. + raise TypeError( + "incompatible type for a datetime/timedelta " + "operation [{name}]".format(name=op.__name__) + ) + raise + + # We do not pass dtype to ensure that the Series constructor + # does inference in the case where `result` has object-dtype. + return construct_result(left, result, index=left.index, name=res_name) lvalues = left.values rvalues = right From 6cfc3203ec417582b0fff31aef601728691f29a6 Mon Sep 17 00:00:00 2001 From: jbrockmendel Date: Sat, 6 Jul 2019 17:07:54 -0700 Subject: [PATCH 2/2] remove comment --- pandas/core/ops/__init__.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index c74eb890386a6..5738dd9e4a128 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -1713,8 +1713,6 @@ def wrapper(left, right): orig_right = right if is_scalar(right): # broadcast and wrap in a TimedeltaIndex - # TODO: possible perf improvement by using NaTD scalar - # here (GH#24983) assert np.isnat(right) right = np.broadcast_to(right, left.shape) right = pd.TimedeltaIndex(right)