0
0
Pandasdata~10 mins

Why MultiIndex enables hierarchical data in Pandas - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a MultiIndex from two lists.

Pandas
import pandas as pd
index = pd.MultiIndex.from_tuples([1])
print(index)
Drag options to blanks, or click blank then click option'
A[('A', 1), ('B', 2), ('C', 3)]
B['A', 'B', 'C']
C[1, 2, 3]
D['A1', 'B2', 'C3']
Attempts:
3 left
💡 Hint
Common Mistakes
Using a list of strings instead of tuples.
Passing a single list without tuples.
2fill in blank
medium

Complete the code to create a DataFrame with a MultiIndex.

Pandas
import pandas as pd
index = pd.MultiIndex.from_tuples([('A', 1), ('B', 2)])
data = {'value': [10, 20]}
df = pd.DataFrame(data, index=[1])
print(df)
Drag options to blanks, or click blank then click option'
Adata
Bpd.Index(['A', 'B'])
Cindex
D['A', 'B']
Attempts:
3 left
💡 Hint
Common Mistakes
Passing a list instead of the MultiIndex object.
Using the data dictionary as index.
3fill in blank
hard

Fix the error in accessing data using MultiIndex levels.

Pandas
import pandas as pd
index = pd.MultiIndex.from_tuples([('A', 1), ('B', 2)])
data = {'value': [10, 20]}
df = pd.DataFrame(data, index=index)
result = df.loc[[1]]
print(result)
Drag options to blanks, or click blank then click option'
A'A'
B'value'
C1
D('A', 1)
Attempts:
3 left
💡 Hint
Common Mistakes
Using only one level of the index.
Using column names instead of index keys.
4fill in blank
hard

Fill both blanks to create a MultiIndex DataFrame and select data from a specific level.

Pandas
import pandas as pd
index = pd.MultiIndex.from_tuples([('X', 10), ('Y', 20), ('X', 30)])
data = {'score': [100, 200, 300]}
df = pd.DataFrame(data, index=[1])
selected = df.xs([2], level=0)
print(selected)
Drag options to blanks, or click blank then click option'
Aindex
B'X'
C'Y'
Ddata
Attempts:
3 left
💡 Hint
Common Mistakes
Using the data dictionary as index.
Selecting a key not present in level 0.
5fill in blank
hard

Fill both blanks to create a hierarchical dictionary from a DataFrame with MultiIndex.

Pandas
import pandas as pd
index = pd.MultiIndex.from_tuples([('A', 'x'), ('A', 'y'), ('B', 'x')])
data = {'val': [1, 2, 3]}
df = pd.DataFrame(data, index=[1])
hier_dict = {level0: {level1: row['val'] for level1, row in df.loc[level0].iterrows()} for level0 in df.index.[2]
print(hier_dict)
Drag options to blanks, or click blank then click option'
Aindex
Blevels
Cunique(level=0)
Dvalues
Attempts:
3 left
💡 Hint
Common Mistakes
Using levels instead of unique(level=0).
Using values which returns all index tuples.