# How to make a multi-index in Pandas?

PandasServer Side ProgrammingProgramming

#### Data Analysis using NumPy and Pandas

19 Lectures 8 hours

#### Pandas with Python

24 Lectures 6 hours

#### Pandas Crash Course for begineers : Numpy + Pandas + Matplotlib

Most Popular

63 Lectures 6 hours

To make a multi-index in Pandas, we can use groupby with list of columns.

## Steps

• Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.

• Print the input DataFrame.

• Print the index of DataFrame count.

• Use groupby to get different levels of a hierarchical index and count it.

• Print the mulitindex set in step 4.

## Example

Live Demo

import pandas as pd

df = pd.DataFrame(
{
"x": [5, 2, 1, 9],
"y": [4, 1, 5, 10],
"z": [4, 1, 5, 0]
}
)
print "Input DataFrame is:", df
print "Default index: ", df.count().index

df1 = df.groupby(["x", "y"]).count()
print "Multi index is like: ", df1.index

## Output

Input DataFrame is:
x  y  z
0  5  4  4
1  2  1  1
2  1  5  5
3  9 10  0

Default index: Index(['x', 'y', 'z'], dtype='object')

Multi index is like:
MultiIndex([(1, 5),
(2, 1),
(5, 4),
(9, 10)],
names=['x', 'y'])
Updated on 30-Aug-2021 10:11:46