Python | Панды Series.xs
Python - отличный язык для анализа данных, в первую очередь из-за фантастической экосистемы пакетов Python, ориентированных на данные. Pandas - один из таких пакетов, который значительно упрощает импорт и анализ данных.
Серия Pandas - это одномерный массив ndarray с метками осей. Этикетки не обязательно должны быть уникальными, но должны быть хешируемого типа. Объект поддерживает индексирование как на основе целых чисел, так и на основе меток и предоставляет множество методов для выполнения операций, связанных с индексом.
Pandas Series.xs() function return a cross-section from the Series/DataFrame for the given key value.
Syntax:Series.xs(key, axis=0, level=None, drop_level=True)
Parameters :
key : Label contained in the index, or partially in a MultiIndex.
axis : Axis to retrieve cross-section on.
level : In case of a key partially contained in a MultiIndex, indicate which levels are used. Levels can be referred by label or position.
drop_level : If False, returns object with same levels as self.Returns : Series or DataFrame
Example #1: Use Series.xs() function to return a cross-section of the given Series object for the passed key value.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(["New York", "Chicago", "Toronto", "Lisbon", "Rio"]) # Creating the row axis labelssr.index = ["City 1", "City 2", "City 3", "City 4", "City 5"] # Print the seriesprint(sr) |
Output :
Now we will use Series.xs() function to return the cross-section for the given series object.
# return cross-section corresponding to# the "City 4" labelsr.xs(key = "City 4") |
Output :
As we can see in the output, the Series.xs() function has returned ‘Lisbon’ as the cross-section for the given Series object.
Example #2 : Use Dataframe.xs() function to return a cross-section of the given Dataframe object for the passed key value.
# importing pandas as pdimport pandas as pd # Creating the Dataframedf = pd.DataFrame({"num_legs": [4, 4, 2, 2], "num_wings": [0, 0, 2, 2], "class": ["Mammal", "Mammal", "Mammal", "Bird"], "animal": ["Cow", "Elephant", "Deer", "Sparrow"], "locomotion": ["Walks", "Walks", "Walks", "Flies"]}) # setting the indexdf = df.set_index(["class", "animal", "locomotion"]) # Print the Dataframeprint(df) |
Выход :
Now we will use Dataframe.xs() function to return the cross-section for the given Dataframe object.
# return cross-section corresponding to# the "Mammal" labelsr.xs(key = "Mammal") |
Output :
As we can see in the output, the Dataframe.xs() function has returned the cross-section of the given Dataframe object for the passed key value.
Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.