Skip to content

Commit 0960395

Browse files
committed
BUG: Cast a key to NaT before get loc from Index
pd.NaT, None, float('nan') and np.nan are converted NaT in TestTimedeltas. So we should convert keys if keys are these value. Fix pandas-dev#13603
1 parent d7c028d commit 0960395

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

doc/source/whatsnew/v0.19.0.txt

+2
Original file line numberDiff line numberDiff line change
@@ -614,3 +614,5 @@ Bug Fixes
614614
- Bug in ``groupby`` with ``as_index=False`` returns all NaN's when grouping on multiple columns including a categorical one (:issue:`13204`)
615615

616616
- Bug where ``pd.read_gbq()`` could throw ``ImportError: No module named discovery`` as a result of a naming conflict with another python package called apiclient (:issue:`13454`)
617+
618+
- Bug in Checking for any NaT-like objects in a `TimedeltaIndex` always returns ``True`` (:issue:`13603`)

pandas/tseries/tdi.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -697,6 +697,10 @@ def get_loc(self, key, method=None, tolerance=None):
697697
-------
698698
loc : int
699699
"""
700+
701+
if isnull(key):
702+
key = tslib.NaT
703+
700704
if tolerance is not None:
701705
# try converting tolerance now, so errors don't get swallowed by
702706
# the try/except clauses below
@@ -754,7 +758,7 @@ def _maybe_cast_slice_bound(self, label, side, kind):
754758
def _get_string_slice(self, key, use_lhs=True, use_rhs=True):
755759
freq = getattr(self, 'freqstr',
756760
getattr(self, 'inferred_freq', None))
757-
if is_integer(key) or is_float(key):
761+
if is_integer(key) or is_float(key) or key is tslib.NaT:
758762
self._invalid_indexer('slice', key)
759763
loc = self._partial_td_slice(key, freq, use_lhs=use_lhs,
760764
use_rhs=use_rhs)

pandas/tseries/tests/test_timedeltas.py

+19
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,25 @@ class TestTimedeltas(tm.TestCase):
3030
def setUp(self):
3131
pass
3232

33+
def test_get_loc_nat(self):
34+
tidx = TimedeltaIndex(['1 days 01:00:00', 'NaT', '2 days 01:00:00'])
35+
36+
self.assertEqual(tidx.get_loc(pd.NaT), 1)
37+
self.assertEqual(tidx.get_loc(None), 1)
38+
self.assertEqual(tidx.get_loc(float('nan')), 1)
39+
self.assertEqual(tidx.get_loc(np.nan), 1)
40+
41+
def test_contains(self):
42+
# Checking for any NaT-like objects
43+
# GH 13603
44+
td = to_timedelta(range(5), unit='d') + pd.offsets.Hour(1)
45+
for v in [pd.NaT, None, float('nan'), np.nan]:
46+
self.assertFalse((v in td))
47+
48+
td = to_timedelta([pd.NaT])
49+
for v in [pd.NaT, None, float('nan'), np.nan]:
50+
self.assertTrue((v in td))
51+
3352
def test_construction(self):
3453

3554
expected = np.timedelta64(10, 'D').astype('m8[ns]').view('i8')

0 commit comments

Comments
 (0)