Skip to content

Commit 1d92c77

Browse files
jbrockmendeljreback
authored andcommitted
REF: Avoid dispatching Series ops to pd.Index (#27268)
1 parent b377a78 commit 1d92c77

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

pandas/core/ops/__init__.py

+25-4
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
ABCSeries,
4444
ABCSparseArray,
4545
ABCSparseSeries,
46+
ABCTimedeltaArray,
4647
)
4748
from pandas.core.dtypes.missing import isna, notna
4849

@@ -1703,10 +1704,30 @@ def wrapper(left, right):
17031704
# Note: we cannot use dispatch_to_index_op because
17041705
# that may incorrectly raise TypeError when we
17051706
# should get NullFrequencyError
1706-
result = op(pd.Index(left), right)
1707-
return construct_result(
1708-
left, result, index=left.index, name=res_name, dtype=result.dtype
1709-
)
1707+
orig_right = right
1708+
if is_scalar(right):
1709+
# broadcast and wrap in a TimedeltaIndex
1710+
assert np.isnat(right)
1711+
right = np.broadcast_to(right, left.shape)
1712+
right = pd.TimedeltaIndex(right)
1713+
1714+
assert isinstance(right, (pd.TimedeltaIndex, ABCTimedeltaArray, ABCSeries))
1715+
try:
1716+
result = op(left._values, right)
1717+
except NullFrequencyError:
1718+
if orig_right is not right:
1719+
# i.e. scalar timedelta64('NaT')
1720+
# We get a NullFrequencyError because we broadcast to
1721+
# TimedeltaIndex, but this should be TypeError.
1722+
raise TypeError(
1723+
"incompatible type for a datetime/timedelta "
1724+
"operation [{name}]".format(name=op.__name__)
1725+
)
1726+
raise
1727+
1728+
# We do not pass dtype to ensure that the Series constructor
1729+
# does inference in the case where `result` has object-dtype.
1730+
return construct_result(left, result, index=left.index, name=res_name)
17101731

17111732
lvalues = left.values
17121733
rvalues = right

0 commit comments

Comments
 (0)