0
0
Data Analysis Pythondata~10 mins

MultiIndex (hierarchical indexing) in Data Analysis Python - Interactive Code Practice

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.

Data Analysis Python
import pandas as pd
levels = [['A', 'B'], [1, 2]]
index = pd.MultiIndex.from_product([1])
print(index)
Drag options to blanks, or click blank then click option'
A[1, 2]
B['A', 'B']
Clevels
Dpd.Index(levels)
Attempts:
3 left
💡 Hint
Common Mistakes
Passing a single list instead of a list of lists.
Passing only one level instead of both.
2fill in blank
medium

Complete the code to create a MultiIndex from tuples.

Data Analysis Python
import pandas as pd
arrays = [('A', 1), ('A', 2), ('B', 1), ('B', 2)]
index = pd.MultiIndex.from_tuples([1])
print(index)
Drag options to blanks, or click blank then click option'
Aarrays
Barrays[0]
Ctuple(arrays)
Dlist(arrays)
Attempts:
3 left
💡 Hint
Common Mistakes
Passing a single tuple instead of a list of tuples.
Converting the list unnecessarily.
3fill in blank
hard

Fix the error in the code to access the second level of the MultiIndex.

Data Analysis Python
import pandas as pd
index = pd.MultiIndex.from_tuples([('A', 1), ('B', 2)])
second_level = index.[1][1]
print(second_level)
Drag options to blanks, or click blank then click option'
Alevels
Bcodes
Clabels
Dvalues
Attempts:
3 left
💡 Hint
Common Mistakes
Using labels which is deprecated.
Trying to access levels which gives unique values, not codes.
4fill in blank
hard

Fill both blanks to create a DataFrame with a MultiIndex and select data for 'B'.

Data Analysis Python
import pandas as pd
index = pd.MultiIndex.from_tuples([('A', 1), ('B', 2), ('B', 3)])
data = pd.DataFrame({'value': [10, 20, 30]}, index=[1])
selected = data.loc[[2]]
print(selected)
Drag options to blanks, or click blank then click option'
Aindex
B'B'
C'A'
Ddata
Attempts:
3 left
💡 Hint
Common Mistakes
Using the DataFrame itself as index.
Selecting with the wrong label.
5fill in blank
hard

Fill all three blanks to create a MultiIndex DataFrame and filter rows where second level is greater than 1.

Data Analysis Python
import pandas as pd
index = pd.MultiIndex.from_tuples([('X', 1), ('X', 2), ('Y', 3)])
data = pd.DataFrame({'score': [5, 10, 15]}, index=[1])
filtered = data[[[2] for [3] in data.index if [2] > 1]]
print(filtered)
Drag options to blanks, or click blank then click option'
Aindex
Bx[1]
Cx
Ddata.index
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong variable names in the list comprehension.
Accessing the wrong level of the MultiIndex.