Skip to content

Commit 2ea12bc

Browse files
author
Christoph Paulik
committed
BUG: Fix length 1 .loc slicing with datetime string GH16071
1 parent b17e286 commit 2ea12bc

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

doc/source/whatsnew/v0.20.0.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -557,6 +557,7 @@ Other Enhancements
557557
- The ``display.show_dimensions`` option can now also be used to specify
558558
whether the length of a ``Series`` should be shown in its repr (:issue:`7117`).
559559
- ``parallel_coordinates()`` has gained a ``sort_labels`` keyword arg that sorts class labels and the colours assigned to them (:issue:`15908`)
560+
- ``loc`` indexer with datetime strings now works correctly for length 1 DataFrames and is consistent with the behaviour of using a ``datetime.datetime`` object (:issue:`16071')
560561

561562

562563
.. _ISO 8601 duration: https://en.wikipedia.org/wiki/ISO_8601#Durations

pandas/core/indexes/datetimes.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1470,8 +1470,9 @@ def _maybe_cast_slice_bound(self, label, side, kind):
14701470
# [parsed, parsed + 1 freq)
14711471
# because label may be passed to searchsorted
14721472
# the bounds need swapped if index is reverse sorted and has a
1473-
# length (is_monotonic_decreasing gives True for empty index)
1474-
if self.is_monotonic_decreasing and len(self):
1473+
# length > 1 (is_monotonic_decreasing gives True for empty
1474+
# and length 1 index)
1475+
if self.is_monotonic_decreasing and len(self) > 1:
14751476
return upper if side == 'left' else lower
14761477
return lower if side == 'left' else upper
14771478
else:

pandas/tests/indexing/test_loc.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -628,3 +628,22 @@ def test_loc_empty_list_indexer_is_ok(self):
628628
tm.assert_frame_equal(df.loc[[]], df.iloc[:0, :],
629629
check_index_type=True,
630630
check_column_type=True)
631+
632+
633+
def test_loc_datetime_length_one():
634+
"""
635+
Test if DataFrame with length one is properly sliced
636+
by .loc.
637+
"""
638+
from datetime import datetime
639+
df = pd.DataFrame(columns=['1'],
640+
index=pd.date_range('2016-10-01T00:00:00',
641+
'2016-10-01T23:59:59'))
642+
df_sliced_dt = df.loc[datetime(2016, 10, 1):]
643+
tm.assert_frame_equal(df, df_sliced_dt)
644+
645+
df = pd.DataFrame(columns=['1'],
646+
index=pd.date_range('2016-10-01T00:00:00',
647+
'2016-10-01T23:59:59'))
648+
df_sliced_str = df.loc['2016-10-01T00:00:00':]
649+
tm.assert_frame_equal(df, df_sliced_str)

0 commit comments

Comments
 (0)