From 6beb9b36f7025b7edd56d7e5068df768471f7ba5 Mon Sep 17 00:00:00 2001 From: Mak Sze Chun Date: Tue, 19 Feb 2019 21:46:03 +0800 Subject: [PATCH] [BUG] exception handling of MultiIndex.__contains__ too narrow (#25268) --- doc/source/whatsnew/v0.25.0.rst | 3 +-- pandas/core/indexes/multi.py | 2 +- pandas/tests/indexing/multiindex/test_multiindex.py | 8 ++++++++ 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst index 686c5ad0165e78..9d33c651ef2834 100644 --- a/doc/source/whatsnew/v0.25.0.rst +++ b/doc/source/whatsnew/v0.25.0.rst @@ -149,10 +149,9 @@ Missing MultiIndex ^^^^^^^^^^ +- Bug in which incorrect exception raised by :meth:`pd.Timedelta` when testing the membership of :class:`MultiIndex` (:issue:`24570`) - - -- - I/O ^^^ diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index efb77b5d155a1b..c19b6f61f2caac 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -840,7 +840,7 @@ def __contains__(self, key): try: self.get_loc(key) return True - except (LookupError, TypeError): + except (LookupError, TypeError, ValueError): return False contains = __contains__ diff --git a/pandas/tests/indexing/multiindex/test_multiindex.py b/pandas/tests/indexing/multiindex/test_multiindex.py index 4f5517f89e852c..ccf017489e0465 100644 --- a/pandas/tests/indexing/multiindex/test_multiindex.py +++ b/pandas/tests/indexing/multiindex/test_multiindex.py @@ -84,3 +84,11 @@ def test_multi_nan_indexing(self): name='a'), Index(['C1', 'C2', 'C3', 'C4'], name='b')]) tm.assert_frame_equal(result, expected) + + def test_contains(self): + # GH 24570 + tx = pd.timedelta_range('09:30:00', '16:00:00', freq='30 min') + idx = MultiIndex.from_arrays([tx, np.arange(len(tx))]) + assert tx[0] in idx + assert 'element_not_exit' not in idx + assert '0 day 09:30:00' in idx