How to Create a Dataframe With Multi Index in Python

To create a dataframe with multi index in Python, you can use the pandas.MultiIndex() function.

The following example shows how to create a dataframe with multi index in Python using the pandas.MultiIndex() function.

Using pandas.MultiIndex() Function

We can use the pandas.MultiIndex() function to create a dataframe with multi index.

Suppose we have the following data:

# Import pandas library
import pandas as pd

# Declare index
array1 = [1, 2, 3, 4, 5, 6]
array2 = ["a", "b", "c", "d", "e", "f"]

# Create MultiIndex 
multi_index = pd.MultiIndex.from_arrays([array1, array2], names=['Index1', 'Index2'])

# Create dataframe
Office_Stuff = pd.DataFrame({
    'Date': ['01-03-2023', '01-03-2023', '01-03-2023', '01-03-2023', '02-03-2023', '02-03-2023'],
    'Product_Code': ['A-101', 'A-102', 'A-103', 'B-101', 'B-102', 'B-104'],
    'Product_Name': ['Laptop', 'Mobile', 'Printer', 'Keyboard', 'Scanner', 'Mouse'],
    'Price': [4500, 550, 250, 50, 350, 50],
    'Status': [1, 1, 1, 0, 1, 1]
}, index=multi_index)

# Show dataframe
print(Office_Stuff)

Output: 👇️

                     Date Product_Code Product_Name  Price  Status
Index1 Index2                                                     
1      a       01-03-2023        A-101       Laptop   4500       1
2      b       01-03-2023        A-102       Mobile    550       1
3      c       01-03-2023        A-103      Printer    250       1
4      d       01-03-2023        B-101     Keyboard     50       0
5      e       02-03-2023        B-102      Scanner    350       1
6      f       02-03-2023        B-104        Mouse     50       1

In this example, we use the pandas.MultiIndex() function to create a multi-index for the dataframe Office_Stuff.

The output shows the dataframe with multiple indices.

Conclusion

We can use the pandas.MultiIndex() function to create a dataframe with multi index in Python.