w3resource

Set MultiIndex and access data in Pandas DataFrame


3. 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.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to set a MultiIndex using columns 'X' and 'Y' and then retrieve data for a specific tuple index.
  • Write a Pandas program to create a MultiIndex from two columns and then access a subset of data using a partial index key.
  • Write a Pandas program to build a MultiIndex DataFrame and use .loc to extract a row corresponding to a given index combination.
  • Write a Pandas program to create a MultiIndex DataFrame and then sort the DataFrame by the MultiIndex levels.

Go to:


PREV : Select Specific Columns ('X' and 'Y').
NEXT : Slice DataFrame Based on MultiIndex Levels.

Python-Pandas Code Editor:

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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.