0
0
Pandasdata~10 mins

Creating MultiIndex DataFrames in Pandas - Interactive 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.

Pandas
import pandas as pd
levels = [['A', 'B'], ['one', 'two']]
index = pd.MultiIndex.from_tuples([1])
print(index)
Drag options to blanks, or click blank then click option'
A[('A', 'one'), ('A', 'two'), ('B', 'one'), ('B', 'two')]
B[('A', 'one'), ('B', 'two')]
C['A', 'B', 'one', 'two']
D['A', 'one', 'B', 'two']
Attempts:
3 left
💡 Hint
Common Mistakes
Using a flat list instead of a list of tuples.
Not including all combinations of the levels.
2fill in blank
medium

Complete the code to create a MultiIndex using from_product.

Pandas
import pandas as pd
levels = [['X', 'Y'], [1, 2]]
index = pd.MultiIndex.[1](levels)
print(index)
Drag options to blanks, or click blank then click option'
Afrom_tuples
Bfrom_arrays
Cfrom_product
Dfrom_frame
Attempts:
3 left
💡 Hint
Common Mistakes
Using from_tuples without providing tuples.
Confusing from_arrays with from_product.
3fill in blank
hard

Fix the error in creating a MultiIndex from arrays.

Pandas
import pandas as pd
arrays = [['a', 'a', 'b', 'b'], [1, 2, 1, 2]]
index = pd.MultiIndex.from_arrays([1])
print(index)
Drag options to blanks, or click blank then click option'
A[arrays]
Barrays
Carrays[0]
Darrays[1]
Attempts:
3 left
💡 Hint
Common Mistakes
Wrapping the arrays list inside another list.
Passing only one array instead of both.
4fill in blank
hard

Fill both blanks to create a DataFrame with a MultiIndex from tuples and set column names.

Pandas
import pandas as pd
tuples = [('red', 1), ('red', 2), ('blue', 1), ('blue', 2)]
index = pd.MultiIndex.[1](tuples, names=[2])
data = [10, 20, 30, 40]
df = pd.DataFrame(data, index=index, columns=['value'])
print(df)
Drag options to blanks, or click blank then click option'
Afrom_tuples
Bfrom_product
C['color', 'number']
D('color', 'number')
Attempts:
3 left
💡 Hint
Common Mistakes
Using from_product instead of from_tuples.
Passing a tuple instead of a list for names.
5fill in blank
hard

Fill all three blanks to create a MultiIndex DataFrame from product, set names, and assign columns.

Pandas
import pandas as pd
levels = [['A', 'B'], [1, 2]]
index = pd.MultiIndex.[1](levels, names=[2])
data = [[5, 10], [15, 20], [25, 30], [35, 40]]
df = pd.DataFrame(data, index=index, columns=[3])
print(df)
Drag options to blanks, or click blank then click option'
Afrom_product
B['level_1', 'level_2']
C['col1', 'col2']
Dfrom_tuples
Attempts:
3 left
💡 Hint
Common Mistakes
Using from_tuples instead of from_product.
Passing tuples instead of lists for names or columns.