</>
Skip to content
Pandas lessons (38/42)

Pandas — MultiIndex

Create MultiIndex

import pandas as pd

arrays = [['A', 'A', 'B', 'B'], ['one', 'two', 'one', 'two']]
index = pd.MultiIndex.from_arrays(arrays, names=['first', 'second'])
df = pd.DataFrame({'data': [1, 2, 3, 4]}, index=index)

Select with MultiIndex

# Select level
print(df.loc['A'])

# Select specific
print(df.loc[('A', 'one')])

Swap levels

df = df.swaplevel()

Sort index

df = df.sort_index()

Stack/Unstack

# Unstack level
unstacked = df.unstack(level='second')

# Stack
stacked = unstacked.stack()

Mini Practice

  1. Create MultiIndex
  2. Select by level
  3. Swap levels
  4. Use stack/unstack

Up Next

Continue with Resample - Time resampling.

Related Topics

Frequently Asked Questions about MultiIndex

What is MultiIndex in Pandas?

MultiIndex is a fundamental concept in Pandas. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn MultiIndex?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn MultiIndex.

Why is MultiIndex important in Pandas?

MultiIndex is essential for Pandas development. Understanding this concept will help you write better code and solve real-world problems more effectively.