Python | Панды Series.searchsorted ()
Python - отличный язык для анализа данных, в первую очередь из-за фантастической экосистемы пакетов Python, ориентированных на данные. Pandas - один из таких пакетов, который значительно упрощает импорт и анализ данных.
Pandas searchsorted() is a method for sorted series. It allows user to pass values as parameter which are to be inserted into the series and returns array of positions where values can be inserted so that the order of series is still preserved.
Syntax: Series.searchsorted(value, side=’left’, sorter=None)
Parameters:
value: Values to be inserted into self (Caller series)
side: ‘left’ or ‘right’, returns first or last suitable position for value respectively
sorter: Array of indices which is of same size as series is passed. If sorter is None, caller series must be in ascending order, otherwise sorter should be array of indices that sorts it.Return type: Array of indices
Пример №1:
In this example, searchsorted() method is called on a sorted series and 3-values are passed as parameter.
# importing pandas module import pandas as pd # importing numpy module import numpy as np # creating listlist =[0, 2, 3, 7, 12, 12, 15, 24] # creating seriesseries = pd.Series(list) # values to be insertedval =[1, 7, 14] # calling .searchsorted() methodresult = series.searchsorted(value = val) # displayresult |
Выход:
массив ([1, 3, 6])
Как показано в выходных данных, был возвращен индекс каждого значения. Поскольку 7 уже существует в серии, для него была возвращена позиция индекса 6 из-за бокового параметра по умолчанию, который равен 'left'. Следовательно, он возвращает левый индекс в случае равных значений.
Example #2: Searchsorted() on series of string.
In this example, a sorted series of some fruits name is made out of a python list using Pandas Series method. After that a list of two strings is passed as value parameter of searchsorted() method.
# importing pandas module import pandas as pd # importing numpy module import numpy as np # creating listdata =["apple", "banana", "mango", "pineapple", "pizza"] # creating seriesseries = pd.Series(data) # values to be insertedval =["grapes", "watermelon"] # calling .searchsorted() methodresult = series.searchsorted(value = val) # displayresult |
Выход:
массив ([2, 5])
Как показано в выходных данных, позиция индекса возвращается для каждого значения в переданном списке, так что порядок серий будет сохранен, если значения будут помещены в этот индекс.
Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.