Skip to content

Commit ebd6666

Browse files
jbrockmendeljreback
authored andcommitted
Fix+Test Timedelta.__mul__(nan) (#23342)
1 parent 47e45ed commit ebd6666

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

pandas/_libs/tslibs/timedeltas.pyx

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1213,6 +1213,12 @@ class Timedelta(_Timedelta):
12131213
return other.delta * self
12141214
return NotImplemented
12151215

1216+
elif util.is_nan(other):
1217+
# i.e. np.nan, but also catch np.float64("NaN") which would
1218+
# otherwise get caught by the hasattr(other, "dtype") branch
1219+
# incorrectly return a np.timedelta64 object.
1220+
return NaT
1221+
12161222
elif hasattr(other, 'dtype'):
12171223
# ndarray-like
12181224
return other * self.to_timedelta64()
@@ -1240,6 +1246,12 @@ class Timedelta(_Timedelta):
12401246
# convert to Timedelta below
12411247
pass
12421248

1249+
elif util.is_nan(other):
1250+
# i.e. np.nan, but also catch np.float64("NaN") which would
1251+
# otherwise get caught by the hasattr(other, "dtype") branch
1252+
# incorrectly return a np.timedelta64 object.
1253+
return NaT
1254+
12431255
elif hasattr(other, 'dtype'):
12441256
return self.to_timedelta64() / other
12451257

pandas/tests/scalar/timedelta/test_arithmetic.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,14 @@ def test_td_mul_nat(self, op, td_nat):
277277
with pytest.raises(TypeError):
278278
op(td, td_nat)
279279

280+
@pytest.mark.parametrize('nan', [np.nan, np.float64('NaN'), float('nan')])
281+
@pytest.mark.parametrize('op', [operator.mul, ops.rmul])
282+
def test_td_mul_nan(self, op, nan):
283+
# np.float64('NaN') has a 'dtype' attr, avoid treating as array
284+
td = Timedelta(10, unit='d')
285+
result = op(td, nan)
286+
assert result is NaT
287+
280288
@pytest.mark.parametrize('op', [operator.mul, ops.rmul])
281289
def test_td_mul_scalar(self, op):
282290
# GH#19738
@@ -328,6 +336,16 @@ def test_td_div_numeric_scalar(self):
328336
assert isinstance(result, Timedelta)
329337
assert result == Timedelta(days=2)
330338

339+
@pytest.mark.parametrize('nan', [np.nan, np.float64('NaN'), float('nan')])
340+
def test_td_div_nan(self, nan):
341+
# np.float64('NaN') has a 'dtype' attr, avoid treating as array
342+
td = Timedelta(10, unit='d')
343+
result = td / nan
344+
assert result is NaT
345+
346+
result = td // nan
347+
assert result is NaT
348+
331349
# ---------------------------------------------------------------
332350
# Timedelta.__rdiv__
333351

0 commit comments

Comments
 (0)