Python | Pandas Index.get_loc ()

Python Methods and Functions

Index.get_loc() Pandas Index.get_loc() returns an integer location, slice or boolean mask for the requested label. The function works with both sorted and unsorted indices. It provides various options if the passed value is not in the index. you can return the previous or next value to the passed value only if the index labels are sorted.

Syntax: Index.get_loc (key, method = None, tolerance = None)

Parameters:
key: label
method: {None, 'pad' / ' ffill ',' backfill '/' bfill ',' nearest '}, optional
- & gt;  default: exact matches only.
- & gt;  pad / ffill: find the PREVIOUS index value if no exact match.
- & gt;  backfill / bfill: use NEXT index value if no exact match
- & gt;  nearest: use the NEAREST index value if no exact match. Tied distances are broken by preferring the larger index value.

Returns: loc: int if unique index, slice if monotonic index, else mask

Example # 1: Use Index.get_loc () to find the location of the passed value.

# import pandas as pd

import pandas as pd

 
# Create index

idx = pd.Index ([ 'Labrador' , 'Beagle' , ' Labrador' ,

'Lhasa' , ' Husky' , 'Beagle' ])

  
# Print index
idx

Output:

Let's find out where Lhasa is in the index.

# Print the location of the passed value
idx.get_loc ('Lhasa)

Output:

Like us we see in the output, Index.get_loc () will return La 3, indicating that the passed value is present at that location in the index.

Example # 2: Use Index.get_loc () to find the location of the passed in values. If the passed value is not in the index, then the location of the previous value is returned, which is just less than the passed value.

# import pandas as pd

import pandas as pd

  
# Create index

idx = pd.Index ([ 1 , 2 , 3 , 14 , 25 , 37 , 48 ,   69 , 100 ])

 
# Print index
idx

Output:

Find the position of the value 33 in the index.

# Find position 33 in the index.
# If not, we will forward it
# fill and return the position of the previous value.

idx.get_loc ( 33 , method = 'ffill' )

Output:

As we can see, the function returned the result 3. Since 33 is not in the index, but in sorted order, the value that is less than 33 is 25, and its location is 4. So the result is 4 We do not set the method parameter, it will result in an error if the value is missing.