Set Columns as Multiindex in pandas DataFrame in Python (Example Code)
This post demonstrates how to set certain columns of a pandas DataFrame as a multiindex in Python.
Preparing the Example
import pandas as pd # Import pandas library in Python |
import pandas as pd # Import pandas library in Python
df = pd.DataFrame({'id_A':range(11, 20), # Creating a pandas DataFrame 'id_B':[101, 101, 102, 102, 102, 102, 103, 103, 103], 'id_C':[1001, 1001, 1001, 1001, 1001, 1002, 1002, 1002, 1002], 'col1':range(21, 12, - 1), 'col2':['x', 'y', 'y', 'x', 'x', 'x', 'y', 'x', 'y']}) print(df) # id_A id_B id_C col1 col2 # 0 11 101 1001 21 x # 1 12 101 1001 20 y # 2 13 102 1001 19 y # 3 14 102 1001 18 x # 4 15 102 1001 17 x # 5 16 102 1002 16 x # 6 17 103 1002 15 y # 7 18 103 1002 14 x # 8 19 103 1002 13 y |
df = pd.DataFrame({'id_A':range(11, 20), # Creating a pandas DataFrame 'id_B':[101, 101, 102, 102, 102, 102, 103, 103, 103], 'id_C':[1001, 1001, 1001, 1001, 1001, 1002, 1002, 1002, 1002], 'col1':range(21, 12, - 1), 'col2':['x', 'y', 'y', 'x', 'x', 'x', 'y', 'x', 'y']}) print(df) # id_A id_B id_C col1 col2 # 0 11 101 1001 21 x # 1 12 101 1001 20 y # 2 13 102 1001 19 y # 3 14 102 1001 18 x # 4 15 102 1001 17 x # 5 16 102 1002 16 x # 6 17 103 1002 15 y # 7 18 103 1002 14 x # 8 19 103 1002 13 y
Example: Convert pandas DataFrame Columns to Multiindex Using set_index() Function
df_mi = df.set_index(['id_A', 'id_B', 'id_C']) # Define multiindex print(df_mi) # col1 col2 # id_A id_B id_C # 11 101 1001 21 x # 12 101 1001 20 y # 13 102 1001 19 y # 14 102 1001 18 x # 15 102 1001 17 x # 16 102 1002 16 x # 17 103 1002 15 y # 18 103 1002 14 x # 19 103 1002 13 y |
df_mi = df.set_index(['id_A', 'id_B', 'id_C']) # Define multiindex print(df_mi) # col1 col2 # id_A id_B id_C # 11 101 1001 21 x # 12 101 1001 20 y # 13 102 1001 19 y # 14 102 1001 18 x # 15 102 1001 17 x # 16 102 1002 16 x # 17 103 1002 15 y # 18 103 1002 14 x # 19 103 1002 13 y
Related Articles
Furthermore, you could have a look at the related tutorials on this homepage. A selection of interesting tutorials is shown below.