pandas.MultiIndex.get_loc_level — pandas 3.0.0.dev0+2104.ge637b4290d documentation (original) (raw)

MultiIndex.get_loc_level(key, level=0, drop_level=True)[source]#

Get location and sliced index for requested label(s)/level(s).

The get_loc_level method is a more advanced form of get_loc, allowing users to specify not just a label or sequence of labels, but also the level(s) in which to search. This method is useful when you need to isolate particular sections of a MultiIndex, either for further analysis or for slicing and dicing the data. The method provides flexibility in terms of maintaining or dropping levels from the resulting index based on the drop_levelparameter.

Parameters:

keylabel or sequence of labels

The label(s) for which to get the location.

levelint/level name or list thereof, optional

The level(s) in the MultiIndex to consider. If not provided, defaults to the first level.

drop_levelbool, default True

If False, the resulting index will not drop any level.

Returns:

tuple

A 2-tuple where the elements :

Element 0: int, slice object or boolean array.

Element 1: The resulting sliced multiindex/index. If the key contains all levels, this will be None.

Examples

mi = pd.MultiIndex.from_arrays([list("abb"), list("def")], names=["A", "B"])

mi.get_loc_level("b") (slice(1, 3, None), Index(['e', 'f'], dtype='object', name='B'))

mi.get_loc_level("e", level="B") (array([False, True, False]), Index(['b'], dtype='object', name='A'))

mi.get_loc_level(["b", "e"]) (1, None)