Using MultiIndex in Pandas

Using MultiIndex in pandas is like adding layers to your data cake, making it richer and more flavorful. Let’s layer up.

Diving into MultiIndex

MultiIndex, or hierarchical indexing, allows you to work with higher dimensional data while still using the familiar one-dimensional DataFrame structure:

import pandas as pd

# Sample DataFrame with MultiIndex
arrays = [['Fruit', 'Fruit', 'Vegetable', 'Vegetable'], ['Apple', 'Banana', 'Carrot', 'Broccoli']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['Category', 'Product'])

# Create a DataFrame
df = pd.DataFrame({'Stock': [30, 50, 70, 60]}, index=index)
print(df)

This snippet creates a DataFrame with a MultiIndex made from categories and products, allowing for detailed and structured data querying and manipulation.

Navigating through layers of data with MultiIndex in pandas helps you handle complex data structures with ease, bringing depth to your analysis.

Leave a Reply