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

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

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

Pandas str.index() method is used to search and return lowest index 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.index() gives a ValueError.

Syntax: Series.str.index(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 least index of substring if found.

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

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

In this example, ‘e’ is passed as substring. Since ‘e’ exists in all 5 strings, least index of it’s occurrence is returned. 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")
  
# display
short_data

Выход:
Как показано на выходном изображении, наименьший индекс «е» в серии был возвращен и сохранен в новом столбце.


Пример №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.index() method
try:
    short_data["Index Name"]= short_data["Name"].str.index("a")
except Exception as err:
    print(err)
      
# display
short_data

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

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

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