pandas.Index.slice_locs#
- Index.slice_locs(start=None, end=None, step=None)[source]#
Compute slice locations for input labels.
This method determines the integer start and end positions for a label-based slice, which is useful for translating label-based slicing into positional slicing on the underlying data.
- Parameters:
- startlabel, default None
If None, defaults to the beginning.
- endlabel, default None
If None, defaults to the end.
- stepint, defaults None
If None, defaults to 1. Only the sign is used: a negative
stepgives bounds for a reversed slice.
- Returns:
- tuple[int, int]
Returns a tuple of two integers representing the slice locations for the input labels within the index. Use them together with
step, asslice(start, end, step).
See also
Index.get_locGet location for a single label.
Index.get_slice_boundCalculate the slice bound for a single label; used internally by
slice_locsfor each ofstartandend.Index.slice_indexerCompute the slice for input labels, including
step.
Notes
This method only works if the index is monotonic or unique.
If
startorendis not present in a monotonic index, the returned position is the insertion point that preserves ordering (analogous tonumpy.searchsorted()); no error is raised. If the index is not monotonic and the label is missing, aKeyErroris raised.Examples
>>> idx = pd.Index(list("abcd")) >>> idx.slice_locs(start="b", end="c") (1, 3)
startandendneed not be present in the index; for a monotonic index they are mapped to the appropriate insertion positions:>>> idx = pd.Index(list("bcde")) >>> idx.slice_locs(start="a", end="c") (0, 2)
steponly sets the direction; apply it to the returned bounds:>>> idx = pd.Index(list("abcde")) >>> idx.slice_locs(start="b", end="d", step=2) (1, 4) >>> idx[1:4:2] Index(['b', 'd'], dtype='str') >>> idx.slice_locs(start="d", end="b", step=-1) (3, 0) >>> idx[3:0:-1] Index(['d', 'c', 'b'], dtype='str')