w3resource

Set MultiIndex and access data in Pandas DataFrame

Pandas: Advanced Indexing and Slicing Exercise-3 with Solution

Set MultiIndex and Access Data:

Write a Pandas program to set a MultiIndex and access specific data using it.

Sample Solution :

Python Code :

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({
    'X': [1, 6, 8, 3, 7],
    'Y': [5, 2, 9, 4, 1],
    'Z': ['one', 'one', 'two', 'two', 'one']
})

# Set MultiIndex
df = df.set_index(['Z', 'X'])

# Access data using MultiIndex
result = df.loc[('one', 6)]
print(result)

Output:

Y    2
Name: (one, 6), dtype: int64

Explanation:

  • Import pandas library.
  • Create a DataFrame.
  • Set a MultiIndex using columns 'Z' and 'X'.
  • Access data for index ('one', 6).
  • Print the results.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Select specific columns in Pandas DataFrame.
Next: Slice DataFrame with MultiIndex in Pandas.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/pandas/set-multiindex-and-access-data-in-pandas-dataframe.php