Complete the code to create a MultiIndex from two lists.
import pandas as pd levels = [['A', 'B'], [1, 2]] index = pd.MultiIndex.from_product([1]) print(index)
We use pd.MultiIndex.from_product with a list of levels. Here, levels is the list of lists representing each level.
Complete the code to create a MultiIndex from tuples.
import pandas as pd arrays = [('A', 1), ('A', 2), ('B', 1), ('B', 2)] index = pd.MultiIndex.from_tuples([1]) print(index)
The from_tuples method expects a list of tuples. Here, arrays is already a list of tuples.
Fix the error in the code to access the second level of the MultiIndex.
import pandas as pd index = pd.MultiIndex.from_tuples([('A', 1), ('B', 2)]) second_level = index.[1][1] print(second_level)
labels which is deprecated.levels which gives unique values, not codes.In pandas 1.0+, codes holds the integer codes for each level. Accessing index.codes[1] gives the second level codes.
Fill both blanks to create a DataFrame with a MultiIndex and select data for 'B'.
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)
The DataFrame uses index as its index. To select rows where the first level is 'B', use data.loc['B'].
Fill all three blanks to create a MultiIndex DataFrame and filter rows where second level is greater than 1.
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)
The DataFrame uses index as its index. The list comprehension iterates over data.index with variable x. To filter rows where the second level (index position 1) is greater than 1, use x[1] > 1.