Search⌘ K
AI Features

Hierarchical Indexing

Explore hierarchical indexing in pandas to efficiently manage and analyze multi-level indexed data. Understand how to select data across multiple index levels using methods like loc and xs for organized data manipulation.

We'll cover the following...

Hierarchical indexing is another very important feature of pandas. It makes it possible to have multiple (two or more) index levels on an axis. It enables working with higher-dimensional data in a lower-dimensional representation.

This simple example helps to illustrate this point:

Python 3.5
# Importing numpy and Pandas first
import numpy as np
import pandas as pd
# Set a random seed for reproducibility
np.random.seed(42) # You can use any integer as the seed value
# Create a Series with a list of lists (or arrays) as the index:
index = [['a','a','a','b','b','b','c','c','d','d'], # level 1 index
[1,2,3,1,2,3,1,2,1,2]] # level 2 index
# Let's create a Series "ser" with multi-level index (2 in this example)
ser = pd.Series(np.random.randn(10), index=index)
print(ser)

Hierarchical indexing supports partial indexing to select subsets of data. For example, selecting a from the level 1 index returns all associated data along with the ...