What is the DataFrame.xs() method in pandas?
Overview
The xs method is used to obtain a cross-section of a data frame.
Note: Refer to What is pandas in Python to learn more about pandas.
Syntax
DataFrame.xs(key, axis=0, level=None, drop_level=True)
Parameters
key: This is the label in the index. This is a required argument.axis: This is the axis to get cross-section on. The default value is0(i.e.index). Another possible value is1(i.e.columns).level: This indicates which levels are utilized if a key is partially included in a MultiIndex. Labels or positions can be used to refer to the levels.drop_level: This is a boolean argument. IfFalse, it returns the object with the same levels. The default value isTrue.
Example
import numpy as npimport pandas as pdd = {'num_legs': [4, 4, 4, 2, 2],'num_wings': [0, 0, 0, 2, 2],'class': ['mammal', 'mammal', 'mammal', 'bird', 'bird'],'animal': ['tiger', 'lion', 'fox', 'eagle', 'penguin'],'locomotion': ['walks', 'walks', 'walks', 'flies', 'walks']}df = pd.DataFrame(data=d)df = df.set_index(['class', 'animal', 'locomotion'])df2 = df.sort_index()print(df2.xs(('mammal', 'lion')))
Explanation
- Lines 1–2: We import
pandasandnumpy. - Lines 4–8: We create sample data.
- Line 9: We create a pandas data frame.
- Line 10: We set the data frame index using the
set_index()method. - Line 11: We sort the index using the
sort_index()method. - Line 12: We select a portion of the data frame using the
xs()method.