Skip to content

BUG: Index.get_slice_bounds does not accept datetime.date or tz naive datetime.datetimes #35848

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Sep 2, 2020
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion doc/source/whatsnew/v1.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,8 @@ Datetimelike
- Bug in :attr:`DatetimeArray.date` where a ``ValueError`` would be raised with a read-only backing array (:issue:`33530`)
- Bug in ``NaT`` comparisons failing to raise ``TypeError`` on invalid inequality comparisons (:issue:`35046`)
- Bug in :class:`DateOffset` where attributes reconstructed from pickle files differ from original objects when input values exceed normal ranges (e.g months=12) (:issue:`34511`)
-
- Bug in :meth:`DatetimeIndex.get_slice_bound` where ``datetime.date`` objects were not accepted or naive :class:`Timestamp` with a tz-aware :class:`DatetimeIndex` (:issue:`35690`)
- Bug in :meth:`DatetimeIndex.slice_locs` where ``datetime.date`` objects were not accepted (:issue:`34077`)

Timedelta
^^^^^^^^^
Expand Down
8 changes: 6 additions & 2 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -5046,14 +5046,18 @@ def get_slice_bound(self, label, side: str_t, kind) -> int:
int
Index of label.
"""
assert kind in ["loc", "getitem", None]

if side not in ("left", "right"):
raise ValueError(
"Invalid value for side kwarg, must be either "
f"'left' or 'right': {side}"
)

if kind not in ("loc", "getitem", None):
raise ValueError(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should be an AssertionError as this is an internal method (yes I know @RhysU is actually calling it), but its officially public and merely an interface from .loc

"Invalid value for kind kwarg, must be either "
f"'loc' or 'getitem': {kind}"
)

original_label = label

# For datetime indices label may be a string that has to be converted
Expand Down
7 changes: 4 additions & 3 deletions pandas/core/indexes/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -627,7 +627,9 @@ def get_loc(self, key, method=None, tolerance=None):
raise KeyError(orig_key) from err

def _maybe_cast_for_get_loc(self, key) -> Timestamp:
# needed to localize naive datetimes
# needed to localize naive datetimes or dates (GH 35690)
if isinstance(key, date) and not isinstance(key, datetime):
key = datetime.combine(key, time(0, 0))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

won't the Timestamp(key) below do this already?

key = Timestamp(key)
if key.tzinfo is None:
key = key.tz_localize(self.tz)
Expand Down Expand Up @@ -672,8 +674,7 @@ def _maybe_cast_slice_bound(self, label, side: str, kind):
if self._is_strictly_monotonic_decreasing and len(self) > 1:
return upper if side == "left" else lower
return lower if side == "left" else upper
else:
return label
return self._maybe_cast_for_get_loc(label)

def _get_string_slice(self, key: str, use_lhs: bool = True, use_rhs: bool = True):
freq = getattr(self, "freqstr", getattr(self, "inferred_freq", None))
Expand Down
76 changes: 76 additions & 0 deletions pandas/tests/indexes/test_slice_ops.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
from datetime import date, datetime
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think this should go in tests.indexes.datetimes.test_indexing

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am also testing object and numeric Indexes in this file as well. Where should those tests go?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

id put the object ones in tests.indexes.base_class.test_indexing.TestGetSliceBounds and the numeric ones in tests.indexes.numeric.test_indexing.TestGetSliceBounds


import pytest

from pandas import DatetimeIndex, Index, Timestamp, bdate_range


def test_get_slice_bounds_invalid_kind():
with pytest.raises(ValueError, match="Invalid value for kind kwarg"):
DatetimeIndex([]).get_slice_bound(datetime(2020, 1, 1), kind="foo", side="left")


def test_get_slice_bounds_invalid_side():
with pytest.raises(ValueError, match="Invalid value for side kwarg"):
DatetimeIndex([]).get_slice_bound(
datetime(2020, 1, 1), kind=None, side="middle"
)


@pytest.mark.parametrize("kind", ["getitem", "loc", None])
@pytest.mark.parametrize("side, expected", [("left", 4), ("right", 5)])
@pytest.mark.parametrize("data, bound", [(range(6), 4), (list("abcdef"), "e")])
def test_get_slice_bounds_within(kind, side, expected, data, bound):
index = Index(data)
result = index.get_slice_bound(bound, kind=kind, side=side)
assert result == expected


@pytest.mark.parametrize("kind", ["getitem", "loc", None])
@pytest.mark.parametrize("side", ["left", "right"])
@pytest.mark.parametrize(
"data, bound, expected",
[
(range(6), -1, 0),
(range(6), 10, 6),
(list("abcdef"), "x", 6),
(list("bcdefg"), "a", 0),
],
)
def test_get_slice_bounds_outside(kind, side, expected, data, bound):
index = Index(data)
result = index.get_slice_bound(bound, kind=kind, side=side)
assert result == expected


@pytest.mark.parametrize("box", [date, datetime, Timestamp])
@pytest.mark.parametrize("kind", ["getitem", "loc", None])
@pytest.mark.parametrize("side, expected", [("left", 4), ("right", 5)])
def test_get_slice_bounds_datetime_within(box, kind, side, expected, tz_aware_fixture):
# GH 35690
index = bdate_range("2000-01-03", "2000-02-11").tz_localize(tz_aware_fixture)
result = index.get_slice_bound(box(year=2000, month=1, day=7), kind=kind, side=side)
assert result == expected


@pytest.mark.parametrize("box", [date, datetime, Timestamp])
@pytest.mark.parametrize("kind", ["getitem", "loc", None])
@pytest.mark.parametrize("side", ["left", "right"])
@pytest.mark.parametrize("year, expected", [(1999, 0), (2020, 30)])
def test_get_slice_bounds_datetime_outside(
box, kind, side, year, expected, tz_aware_fixture
):
# GH 35690
index = bdate_range("2000-01-03", "2000-02-11").tz_localize(tz_aware_fixture)
result = index.get_slice_bound(box(year=year, month=1, day=7), kind=kind, side=side)
assert result == expected


@pytest.mark.parametrize("box", [date, datetime, Timestamp])
@pytest.mark.parametrize("kind", ["getitem", "loc", None])
def test_slice_datetime_locs(box, kind, tz_aware_fixture):
# GH 34077
index = DatetimeIndex(["2010-01-01", "2010-01-03"]).tz_localize(tz_aware_fixture)
result = index.slice_locs(box(2010, 1, 1), box(2010, 1, 2))
expected = (0, 1)
assert result == expected