diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index c4e1398d0178f..29aace2a94c5a 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -3572,6 +3572,19 @@ def slice_locs(self, start=None, end=None, step=None, kind=None): ------- start, end : int + Notes + ----- + This method only works if the index is monotonic or unique. + + Examples + --------- + >>> idx = pd.Index(list('abcd')) + >>> idx.slice_locs(start='b', end='c') + (1, 3) + + See Also + -------- + Index.get_loc : Get location for a single label """ inc = (step is None or step >= 0) diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 9ffac0832062d..f091a2b74596f 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1924,7 +1924,9 @@ def get_slice_bound(self, label, side, kind): def slice_locs(self, start=None, end=None, step=None, kind=None): """ For an ordered MultiIndex, compute the slice locations for input - labels. They can be tuples representing partial levels, e.g. for a + labels. + + The input labels can be tuples representing partial levels, e.g. for a MultiIndex with 3 levels, you can pass a single value (corresponding to the first level), or a 1-, 2-, or 3-tuple. @@ -1944,7 +1946,32 @@ def slice_locs(self, start=None, end=None, step=None, kind=None): Notes ----- - This function assumes that the data is sorted by the first level + This method only works if the MultiIndex is properly lex-sorted. So, + if only the first 2 levels of a 3-level MultiIndex are lexsorted, + you can only pass two levels to ``.slice_locs``. + + Examples + -------- + >>> mi = pd.MultiIndex.from_arrays([list('abbd'), list('deff')], + ... names=['A', 'B']) + + Get the slice locations from the beginning of 'b' in the first level + until the end of the multiindex: + + >>> mi.slice_locs(start='b') + (1, 4) + + Like above, but stop at the end of 'b' in the first level and 'f' in + the second level: + + >>> mi.slice_locs(start='b', end=('b', 'f')) + (1, 3) + + See Also + -------- + MultiIndex.get_loc : Get location for a label or a tuple of labels. + MultiIndex.get_locs : Get location for a label/slice/list/mask or a + sequence of such. """ # This function adds nothing to its parent implementation (the magic # happens in get_slice_bound method), but it adds meaningful doc. @@ -2015,6 +2042,8 @@ def get_loc(self, key, method=None): See also -------- Index.get_loc : get_loc method for (single-level) index. + MultiIndex.slice_locs : Get slice location given start label(s) and + end label(s). MultiIndex.get_locs : Get location for a label/slice/list/mask or a sequence of such. """ @@ -2368,6 +2397,8 @@ def get_locs(self, seq): See also -------- MultiIndex.get_loc : Get location for a label or a tuple of labels. + MultiIndex.slice_locs : Get slice location given start label(s) and + end label(s). """ # must be lexsorted to at least as many levels