Complete the code to create a MultiIndex from two lists and set it as the DataFrame columns.
import pandas as pd arrays = [['A', 'A', 'B', 'B'], ['one', 'two', 'one', 'two']] index = pd.MultiIndex.from_arrays(arrays, names=['first', 'second']) df = pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]], columns=[1]) print(df)
The index variable holds the MultiIndex object created from the arrays. Setting columns=index applies the MultiIndex as columns.
Complete the code to set the columns of the DataFrame to a MultiIndex created from tuples.
import pandas as pd cols = [('A', 'one'), ('A', 'two'), ('B', 'one'), ('B', 'two')] mi = pd.MultiIndex.from_tuples(cols, names=['first', 'second']) df = pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]]) df.columns = [1] print(df)
df.columns.pd.Index instead of pd.MultiIndex.The variable mi holds the MultiIndex created from tuples. Assigning it to df.columns sets the MultiIndex as columns.
Fix the error in the code to correctly set a MultiIndex as DataFrame columns.
import pandas as pd arrays = [['X', 'X', 'Y', 'Y'], ['a', 'b', 'a', 'b']] mi = pd.MultiIndex.from_arrays(arrays) df = pd.DataFrame([[10, 20, 30, 40], [50, 60, 70, 80]]) df.columns = [1] print(df)
The MultiIndex object mi must be assigned to df.columns. Assigning arrays or other forms causes errors.
Fill both blanks to create a MultiIndex from product of two lists and set it as DataFrame columns.
import pandas as pd levels = [['A', 'B'], ['one', 'two']] mi = pd.MultiIndex.[1](levels) df = pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]]) df.columns = mi.[2](['first', 'second']) print(df)
from_tuples instead of from_product.rename instead of set_names.pd.MultiIndex.from_product creates a MultiIndex from the Cartesian product of the lists. Then set_names assigns names to the levels.
Fill all three blanks to create a MultiIndex from zipped lists, set names, and assign as DataFrame columns.
import pandas as pd arrays = list(zip(['X', 'X', 'Y', 'Y'], ['a', 'b', 'a', 'b'])) mi = pd.MultiIndex.from_tuples([1]) mi = mi.[2](['level1', 'level2']) df = pd.DataFrame([[10, 20, 30, 40], [50, 60, 70, 80]]) df.columns = [3] print(df)
rename instead of set_names.df.columns.The zipped list arrays is used to create the MultiIndex with from_tuples. Then set_names assigns level names. Finally, mi is assigned to df.columns.