Python | Панды Series.str.rindex ()

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

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

Pandas str.rindex() method is used to search and return highest index(First from right side) of a substring in particular section (Between start and end) of every string in a series. This method works in a similar way to str.find() but on not found case, instead of returning -1, str.rindex() gives a ValueError.

Примечание. Этот метод отличается от str.index (). str.rindex () предназначен для обратного поиска. Вывод как str.index (), так и str.rindex () одинаков, если подстрока существует только один раз в строке.

Syntax: Series.str.rindex(sub, start=0, end=None)

Parameters:
sub: String or character to be searched in the text value in series
start: String or character to be searched in the text value in series
end: String or character to be searched in the text value in series

Return type: Series with highest index of substring if found.

Чтобы загрузить набор данных, используемый в следующем примере, щелкните здесь.
В следующих примерах используемый фрейм данных содержит данные некоторых игроков НБА. Изображение фрейма данных до каких-либо операций прилагается ниже.

Пример # 1: Нахождение наивысшего индекса, когда подстрока существует в каждой строке

In this example, ‘e’ is passed as substring. Since ‘e’ exists in all 5 strings, highest index of it’s occurrence is returned. Both index and rindex methods are applied and output is stored in different columns to compare them. Before applying any operations, null rows were removed using .dropna() method.

# importing pandas module 
import pandas as pd
  
# reading csv file from url 
   
# dropping null value columns to avoid errors
data.dropna(inplace = True)
  
# extracting 5 rows
short_data = data.head().copy()
  
# calling str.index() method
short_data["Index Name"]= short_data["Name"].str.index("e")
  
# calling str.rindex() method
short_data["Reverse Index Name"]= short_data["Name"].str.rindex("e")
  
# display
short_data

Output:
As shown in the output image, It can be compared that .index() method returned the least index while the str.rindex() method returned highest index.

 
Example #2:
In this example, ‘a’ is searched in top 5 rows. Since ‘a’ doesn’t exist in every string, value error will be returned. To handle error, try and except is used.

# importing pandas module 
import pandas as pd
  
# reading csv file from url 
   
# dropping null value columns to avoid errors
data.dropna(inplace = True)
  
# extracting 5 rows
short_data = data.head().copy()
  
# calling str.rindex() method
try:
    short_data["Index Name"]= short_data["Name"].str.rindex("a")
except Exception as err:
    print(err)
      
  
# display
short_data

Выход:
Как показано на выходном изображении, в кадре выходных данных отсутствует столбец «Имя индекса», и была напечатана ошибка «подстрока не найдена». Это потому, что str.rindex () возвращает ValueError, если он не найден, и, следовательно, он должен был перейти к исключению case и распечатать ошибку.

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

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