Skip to content

Commit

Permalink
Fix+Test Timedelta.__mul__(nan) (pandas-dev#23342)
Browse files Browse the repository at this point in the history
  • Loading branch information
jbrockmendel authored and tm9k1 committed Nov 19, 2018
1 parent c930100 commit 45b5dc1
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
12 changes: 12 additions & 0 deletions pandas/_libs/tslibs/timedeltas.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -1213,6 +1213,12 @@ class Timedelta(_Timedelta):
return other.delta * self
return NotImplemented

elif util.is_nan(other):
# i.e. np.nan, but also catch np.float64("NaN") which would
# otherwise get caught by the hasattr(other, "dtype") branch
# incorrectly return a np.timedelta64 object.
return NaT

elif hasattr(other, 'dtype'):
# ndarray-like
return other * self.to_timedelta64()
Expand Down Expand Up @@ -1240,6 +1246,12 @@ class Timedelta(_Timedelta):
# convert to Timedelta below
pass

elif util.is_nan(other):
# i.e. np.nan, but also catch np.float64("NaN") which would
# otherwise get caught by the hasattr(other, "dtype") branch
# incorrectly return a np.timedelta64 object.
return NaT

elif hasattr(other, 'dtype'):
return self.to_timedelta64() / other

Expand Down
18 changes: 18 additions & 0 deletions pandas/tests/scalar/timedelta/test_arithmetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,14 @@ def test_td_mul_nat(self, op, td_nat):
with pytest.raises(TypeError):
op(td, td_nat)

@pytest.mark.parametrize('nan', [np.nan, np.float64('NaN'), float('nan')])
@pytest.mark.parametrize('op', [operator.mul, ops.rmul])
def test_td_mul_nan(self, op, nan):
# np.float64('NaN') has a 'dtype' attr, avoid treating as array
td = Timedelta(10, unit='d')
result = op(td, nan)
assert result is NaT

@pytest.mark.parametrize('op', [operator.mul, ops.rmul])
def test_td_mul_scalar(self, op):
# GH#19738
Expand Down Expand Up @@ -328,6 +336,16 @@ def test_td_div_numeric_scalar(self):
assert isinstance(result, Timedelta)
assert result == Timedelta(days=2)

@pytest.mark.parametrize('nan', [np.nan, np.float64('NaN'), float('nan')])
def test_td_div_nan(self, nan):
# np.float64('NaN') has a 'dtype' attr, avoid treating as array
td = Timedelta(10, unit='d')
result = td / nan
assert result is NaT

result = td // nan
assert result is NaT

# ---------------------------------------------------------------
# Timedelta.__rdiv__

Expand Down

0 comments on commit 45b5dc1

Please sign in to comment.