如何找到熊猫数据框的横截面?
有时我们需要找到pandas系列或数据框的横截面。这里的横截面意味着获取指定索引处的值、多个索引处的值、多个索引和级别处的值或指定列和轴处的值等。有一个称为pandas.DataFrame.xs()的函数将有助于这个条件。
pandas.DataFrame.xs()需要一个关键参数,以便在 MultiIndex 中选择特定级别的数据,并从 pandas 数据框中返回横截面。
Syntax: DataFrame.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.
drop_level – If False, returns an object with the same levels as self.
Returns:
Cross-section from the original DataFrame
下面是有助于正确理解 pandas.DataFrame.xs()函数的 Pandas 代码。
Python3
# importing pandas library
import pandas as pd
# Creating a Dictionary
animal_dict = {'num_of_legs': [4, 0, 4, 2, 2, 2],
'num_of_wings': [0, 0, 0, 2, 2, 2],
'class': ['Reptiles', 'Reptiles', 'Reptiles',
'Birds', 'Birds', 'Birds'],
'animal': ['Turtle', 'Snake', 'Crocodile',
'Parrot', 'Owl', 'Hummingbird'],
'locomotion': ['swim_walk', 'swim_crawl', 'swim_walk',
'flies', 'flies', 'flies']}
# Converting to Data frame and setting index
df = pd.DataFrame(data=animal_dict)
df = df.set_index(['class', 'animal', 'locomotion'])
# Displaying Data frame
df
Python3
# Using dataframe.xs() function
# to get values of a specific index
df.xs('Reptiles')
Python3
# Using dataframe.xs() function
# to get values at several indexes
df.xs(('Birds', 'Parrot'))
Python3
# Using dataframe.xs() function
# to get values at specified index
# and level
df.xs('Crocodile', level = 1)
Python3
# Using dataframe.xs() function
# to get values at several indexes
# and levels
df.xs(('Birds', 'flies'),
level=[0, 'locomotion'])
Python3
# Using dataframe.xs() function
# to get values at specified column
# and axis
df.xs('num_of_wings', axis=1)
输出:
示例 1:获取特定索引处的值
蟒蛇3
# Using dataframe.xs() function
# to get values of a specific index
df.xs('Reptiles')
输出:
示例 2:获取多个索引处的值
蟒蛇3
# Using dataframe.xs() function
# to get values at several indexes
df.xs(('Birds', 'Parrot'))
输出:
示例 3:获取指定索引和级别的值
蟒蛇3
# Using dataframe.xs() function
# to get values at specified index
# and level
df.xs('Crocodile', level = 1)
输出:
示例 4:获取多个索引和级别的值
蟒蛇3
# Using dataframe.xs() function
# to get values at several indexes
# and levels
df.xs(('Birds', 'flies'),
level=[0, 'locomotion'])
输出:
示例 5:获取指定列和轴上的值
蟒蛇3
# Using dataframe.xs() function
# to get values at specified column
# and axis
df.xs('num_of_wings', axis=1)
输出: