diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index e9a4ec9328a9b..bcc442189bf11 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -1113,6 +1113,7 @@ Indexing - Bug in :meth:`DataFrame.first_valid_index` and :meth:`DataFrame.last_valid_index` in presence of entire rows of NaNs in the middle of values (:issue:`20499`). - Bug in :class:`IntervalIndex` where some indexing operations were not supported for overlapping or non-monotonic ``uint64`` data (:issue:`20636`) - Bug in ``Series.is_unique`` where extraneous output in stderr is shown if Series contains objects with ``__ne__`` defined (:issue:`20661`) +- Bug in partial string indexing on a ``Series/DataFrame`` with a monotonic decreasing ``DatetimeIndex`` (:issue:`19362`) MultiIndex ^^^^^^^^^^ diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 95e1f8438c704..95186b2e79a16 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -342,7 +342,8 @@ def _format_with_header(self, header, **kwargs): def __contains__(self, key): try: res = self.get_loc(key) - return is_scalar(res) or type(res) == slice or np.any(res) + return (is_scalar(res) or isinstance(res, slice) or + (is_list_like(res) and len(res))) except (KeyError, TypeError, ValueError): return False diff --git a/pandas/tests/indexes/datetimes/test_partial_slicing.py b/pandas/tests/indexes/datetimes/test_partial_slicing.py index f263ac78cd343..4580d9fff31d5 100644 --- a/pandas/tests/indexes/datetimes/test_partial_slicing.py +++ b/pandas/tests/indexes/datetimes/test_partial_slicing.py @@ -91,6 +91,27 @@ def test_slice_duplicate_monotonic(self): expected = Timestamp('2017-01-01') assert result == expected + def test_monotone_DTI_indexing_bug(self): + # GH 19362 + # Testing accessing the first element in a montononic descending + # partial string indexing. + + df = pd.DataFrame(list(range(5))) + date_list = ['2018-01-02', '2017-02-10', '2016-03-10', + '2015-03-15', '2014-03-16'] + date_index = pd.to_datetime(date_list) + df['date'] = date_index + expected = pd.DataFrame({0: list(range(5)), 'date': date_index}) + tm.assert_frame_equal(df, expected) + + df = pd.DataFrame({'A': [1, 2, 3]}, + index=pd.date_range('20170101', + periods=3)[::-1]) + expected = pd.DataFrame({'A': 1}, + index=pd.date_range('20170103', + periods=1)) + tm.assert_frame_equal(df.loc['2017-01-03'], expected) + def test_slice_year(self): dti = DatetimeIndex(freq='B', start=datetime(2005, 1, 1), periods=500)