Python | Панды Index.get_loc ()

Опубликовано: 28 Марта, 2022

Python - отличный язык для анализа данных, в первую очередь из-за фантастической экосистемы пакетов Python, ориентированных на данные. Pandas - один из таких пакетов, который значительно упрощает импорт и анализ данных.

Pandas Index.get_loc() function return integer location, slice or boolean mask for requested label. The function works with both sorted as well as unsorted Indexes. It provides various options if the passed value is not present in the Index. you may choose to return the previous value or the 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
-> default: exact matches only.
-> pad / ffill: find the PREVIOUS index value if no exact match.
-> backfill / bfill: use NEXT index value if no exact match
-> 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() function to find the location of the passed value.

# importing pandas as pd
import pandas as pd
  
# Creating the Index
idx = pd.Index(["Labrador", "Beagle", "Labrador",
                     "Lhasa", "Husky", "Beagle"])
  
# Print the Index
idx

Выход :

let’s find out the location of ‘Lhasa’ in the Index.

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

Output :

As we can see in the output, the Index.get_loc() function has returned 3 indicating that the passed value is present at this location in the Index.
 
Example #2: Use Index.get_loc() function to find the location of the passed value. If the passed value is not present in the Index then return the location of previous value that is just smaller than the passed value.

# importing pandas as pd
import pandas as pd
  
# Creating the Index
idx = pd.Index([1, 2, 3, 14, 25, 37, 48, 69, 100])
  
# Print the Index
idx

Выход :

Let’s find the position of the value 33 in the Index.

# Find the position of 33 in the index.
# If it is not present then we forward 
# fill and return the position of previous value.
idx.get_loc(33, method ="ffill")

Выход :

Как мы видим, функция вернула результат 3. Так как 33 отсутствует в индексе, но в отсортированном порядке значение, которое чуть меньше 33, равно 25, а его местоположение равно 4. Итак, результат равен 4. мы делаем не установлен параметр метода, то это приведет к ошибке, если значение отсутствует.

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.