0
0
Pandasdata~5 mins

xs() for cross-section selection in Pandas

Choose your learning style9 modes available
Introduction

The xs() method helps you pick out specific rows or columns from a DataFrame using labels. It is very useful when working with multi-level indexes.

You want to get all data for a specific label in a multi-level index.
You need to quickly select a row or column by its label without slicing.
You want to extract a cross-section from a DataFrame with hierarchical indexes.
You want to simplify data selection instead of using complex boolean filters.
Syntax
Pandas
DataFrame.xs(key, axis=0, level=None, drop_level=True)

key is the label you want to select.

axis=0 means select rows, axis=1 means select columns.

Examples
Selects rows where the index label is 'label'.
Pandas
df.xs('label')
Selects columns where the column label is 'label'.
Pandas
df.xs('label', axis=1)
Selects data at level 1 of a multi-level index with label 'label'.
Pandas
df.xs('label', level=1)
Sample Program

This code creates a DataFrame with two levels in the index: 'letter' and 'number'. Using xs(), it selects all rows where the 'letter' level is 'A'.

Pandas
import pandas as pd

# Create a DataFrame with multi-level index
index = pd.MultiIndex.from_tuples([
    ('A', 1), ('A', 2), ('B', 1), ('B', 2)
], names=['letter', 'number'])
data = {'value': [10, 20, 30, 40]}
df = pd.DataFrame(data, index=index)

# Use xs to select all rows where letter is 'A'
result = df.xs('A', level='letter')
print(result)
OutputSuccess
Important Notes

If you use drop_level=True (default), the selected level is removed from the index in the result.

You can use xs() on columns by setting axis=1.

Summary

xs() helps pick data by label from rows or columns.

It works well with multi-level indexes to select cross-sections easily.

Remember to specify the level if your index has multiple levels.