Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
pandas

What is the DataFrame.xs() method in pandas?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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 is 0 (i.e. index). Another possible value is 1 (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. If False, it returns the object with the same levels. The default value is True.

Example

import numpy as np
import pandas as pd
d = {'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 pandas and numpy.
  • 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.

RELATED TAGS

python
pandas

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring