Skip to content

Commit 715fa9c

Browse files
committed
clarify-error-message-slice-bound-non-monotonic-index-without-specifying-the-label
1 parent 7b51d3a commit 715fa9c

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

pandas/core/indexes/base.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6868,8 +6868,11 @@ def get_slice_bound(self, label, side: Literal["left", "right"]) -> int:
68686868
try:
68696869
return self._searchsorted_monotonic(label, side)
68706870
except ValueError:
6871-
# raise the original KeyError
6872-
raise err from None
6871+
raise KeyError(
6872+
f"Cannot get {side} slice bound for non-monotonic index "
6873+
f"with a non-specific label: {original_label!r}. "
6874+
"Please specify the label."
6875+
) from err
68736876

68746877
if isinstance(slc, np.ndarray):
68756878
# get_loc may return a boolean array, which

pandas/tests/series/indexing/test_indexing.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -404,6 +404,16 @@ def test_setitem_empty_indexer(indexer, val):
404404
tm.assert_frame_equal(df, expected)
405405

406406

407+
def test_loc_non_monotonic_index_with_non_specific_label():
408+
msg = (
409+
"Cannot get left slice bound for non-monotonic "
410+
"index with a non-specific label: 4"
411+
)
412+
ser = Series([3, 6, 7, 6], index=[3, 8, 7, 6])
413+
with pytest.raises(KeyError, match=msg):
414+
ser.loc[4:7]
415+
416+
407417
class TestDeprecatedIndexers:
408418
@pytest.mark.parametrize("key", [{1}, {1: 1}])
409419
def test_getitem_dict_and_set_deprecated(self, key):

0 commit comments

Comments
 (0)