DataFrame.xs(key, axis=0, level=None, drop_level=True)
返回Series
/DataFrame
的横截面(cross-section)
该方法使用一个关键参数来选择多索引特定级别的数据。
参数: | key : label包含在索引中,或部分包含在多索引中。 axis : {0 或 ‘index’, 1 或 ‘columns’}, 默认 0 轴上检索横截面(cross-section)。 level : 如果key部分包含在多索引中,请指示使用了哪些级别。 级别可以通过label 或 position来引用。 drop_level : 如果为 |
返回: |
与所选索引级别对应的原始 或 |
注意:
xs
不能用于设置值。
多索引切片器是在任何级别上获取/设置值的通用方法。它是xs
功能的超集,参见MultiIndex Slicers。
例子,
>>> d = {'num_legs': [4, 4, 2, 2],
... 'num_wings': [0, 0, 2, 2],
... 'class': ['mammal', 'mammal', 'mammal', 'bird'],
... 'animal': ['cat', 'dog', 'bat', 'penguin'],
... 'locomotion': ['walks', 'walks', 'flies', 'walks']}
>>> df = pd.DataFrame(data=d)
>>> df = df.set_index(['class', 'animal', 'locomotion'])
>>> df
num_legs num_wings
class animal locomotion
mammal cat walks 4 0
dog walks 4 0
bat flies 2 2
bird penguin walks 2 2
获取指定索引处的值
>>> df.xs('mammal')
num_legs num_wings
animal locomotion
cat walks 4 0
dog walks 4 0
bat flies 2 2
获取多个索引处的值
>>> df.xs(('mammal', 'dog'))
num_legs num_wings
locomotion
walks 4 0
获取指定索引和级别(level)的值
>>> df.xs('cat', level=1)
num_legs num_wings
class locomotion
mammal walks 4 0
获取多个索引和级别的值
>>> df.xs(('bird', 'walks'),
... level=[0, 'locomotion'])
num_legs num_wings
animal
penguin 2 2
获取指定列和轴上的值
>>> df.xs('num_wings', axis=1)
class animal locomotion
mammal cat walks 0
dog walks 0
bat flies 2
bird penguin walks 2
Name: num_wings, dtype: int64