Python | Pandas MultiIndex.nlevels



MultiIndex.nlevels Pandas MultiIndex.nlevels returns an integer number of levels in MultiIndex.

Syntax: MultiIndex.nlevels

Example # 1: Use the MultiIndex.nlevels attribute to find the number of levels in the MultiIndex.

# import pandas as pd

import pandas as pd

 
# Create an array

array = [[ 1 , 2 , 3 ], [ ` Sharon` , `Nick` , `Bailey` ]]

  
# Print array

print (array)

Output:

Now let`s create a MultiIndex using this array

# Create MultiIndex

midx = pd .MultiIndex.from_arrays (array, names = ( `Number` , ` Names` ))

 
# Print MultiIndex

print (midx)

Output:

Now we will find the number of levels in MultiIndex.

# Display the number of levels in MultiIndex
midx.nlevels

Output:

As we can see in the output, there are 2 levels in the MultiIndex midx.

Example # 2: Use the MultiIndex.nlevels attribute to find the amount of yro in this MultiIndex.

# import pandas as pd

import pandas as pd

 
# Create an array

array = [[ 1 , 2 , 3 ], [ `Sharon` , `Nick` , ` Bailey` ],

[ `Doctor` , ` Sci entist` , `Physicist` ]]

 
# Print array

print (array)

Output:

Now let`s create MultiIndex using this array

Output:

Now we will find the number of levels in MultiIndex.

# Create MultiIndex

midx = pd.MultiIndex.from_arrays (array, 

names = ( `Ranking` , `Names` , ` Profession` ))

  
# Print MultiIndex

print (midx)

# Display level number in MultiIndex
midx.nlevels

Exit :

As we can see from the output, midex MultiIndex has 3 levels.