Multi-level indexing, also known as hierarchical indexing, is a powerful feature in the Pandas library that allows you to have multiple index levels (row or column) in your data. This enables efficient organization, selection, and slicing of complex datasets where a single index might be insufficient to capture the multidimensional structure of the data.
Multi-level indexing enhances data readability and enables grouping operations, reshaping of datasets, and working with higher-dimensional data in a two-dimensional structure.
This tutorial will cover the following:
A MultiIndex in Pandas is a data structure that allows for multiple index levels in rows and/or columns. It can be used to represent hierarchical relationships within data and perform complex group-by and pivoting operations.
import pandas as pd
index = pd.MultiIndex.from_tuples([('A', 1), ('A', 2), ('B', 1), ('B', 2)])
data = [10, 20, 30, 40]
series = pd.Series(data, index=index)
print(series)
arrays = [['A', 'A', 'B', 'B'], [1, 2, 1, 2]]
index = pd.MultiIndex.from_arrays(arrays, names=('letter', 'number'))
df = pd.DataFrame({'value': [100, 200, 300, 400]}, index=index)
print(df)
df = pd.DataFrame({
'letter': ['A', 'A', 'B', 'B'],
'number': [1, 2, 1, 2],
'value': [100, 200, 300, 400]
})
df = df.set_index(['letter', 'number'])
print(df)
print(df.loc['A']) # Access all rows with outer index 'A'
print(df.loc['A', 2]) # Access specific element
print(df.xs('A')) # Cross-section on first level
print(df.xs(2, level='number')) # Cross-section on second level
print(df.loc[('B', 1)]) # Accessing with tuple
print(df.loc['A']) # All rows where first index is 'A'
idx = pd.IndexSlice
print(df.loc[idx[:, 1], :]) # All rows where second index is 1
print(df.loc[('A', slice(1, 2)), :])
df_reset = df.reset_index()
print(df_reset)
df_new = df_reset.set_index(['letter', 'number'])
print(df_new)
df_swapped = df.swaplevel()
print(df_swapped)
df_sorted = df.sort_index()
print(df_sorted)
df_sorted_lvl1 = df.sort_index(level=1)
print(df_sorted_lvl1)
columns = pd.MultiIndex.from_tuples([('score', 'math'), ('score', 'science'), ('rank', 'math'), ('rank', 'science')])
df_columns = pd.DataFrame([[90, 85, 1, 2], [80, 88, 2, 1]], columns=columns)
print(df_columns)
print(df_columns['score']) # Access all 'score' columns
print(df_columns['score']['math']) # Access 'math' under 'score'
df_swapped_col = df_columns.swaplevel(axis=1)
df_sorted_col = df_swapped_col.sort_index(axis=1)
print(df_sorted_col)
df_unstacked = df.unstack()
print(df_unstacked)
df_stacked = df_unstacked.stack()
print(df_stacked)
print(df.unstack(level='number'))
print(df.stack(level=0))
grouped = df.groupby(level='letter').sum()
print(grouped)
grouped_all = df.groupby(['letter', 'number']).mean()
print(grouped_all)
grouped_reset = grouped_all.reset_index()
print(grouped_reset)
dates = pd.date_range('2024-01-01', periods=4)
stocks = ['AAPL', 'GOOGL']
index = pd.MultiIndex.from_product([dates, stocks], names=['date', 'symbol'])
data = pd.DataFrame({'price': [150, 2800, 152, 2825, 155, 2850, 158, 2900]}, index=index)
print(data)
df_flat = pd.DataFrame({
'region': ['North', 'North', 'South', 'South'],
'year': [2021, 2022, 2021, 2022],
'sales': [100, 150, 80, 120]
})
pivoted = df_flat.pivot(index='region', columns='year', values='sales')
print(pivoted)
pivoted_reset = pivoted.reset_index()
print(pivoted_reset)
df.index.names = ['Region', 'Category']
df = df.sort_index()
Always use IndexSlice for complex slicing to avoid ambiguity.
df_flat = df_columns.copy()
df_flat.columns = ['_'.join(col).strip() for col in df_flat.columns.values]
print(df_flat)
Multi-level indexing in Pandas is a powerful feature that enables complex data analysis using hierarchical relationships in data. Whether it's managing time-series data with multiple attributes or creating pivoted reports, MultiIndex provides the flexibility and control needed for advanced data manipulations.
Key takeaways include:
Mastering MultiIndex equips you with the tools to manipulate high-dimensional data efficiently, making your data pipelines more robust and scalable.
Python is commonly used for developing websites and software, task automation, data analysis, and data visualisation. Since it's relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organising finances.
Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works.
The point is that Java is more complicated to learn than Python. It doesn't matter the order. You will have to do some things in Java that you don't in Python. The general programming skills you learn from using either language will transfer to another.
Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.
6 Top Tips for Learning Python
The following is a step-by-step guide for beginners interested in learning Python using Windows.
Best YouTube Channels to Learn Python
Write your first Python programStart by writing a simple Python program, such as a classic "Hello, World!" script. This process will help you understand the syntax and structure of Python code.
The average salary for Python Developer is ₹5,55,000 per year in the India. The average additional cash compensation for a Python Developer is within a range from ₹3,000 - ₹1,20,000.
Copyrights © 2024 letsupdateskills All rights reserved