Python | Rain MultiIndex.nlevels

Опубликовано: 28 Марта, 2022

Python - отличный язык для анализа данных, в первую очередь из-за фантастической экосистемы пакетов Python, ориентированных на данные. Pandas - один из таких пакетов, который значительно упрощает импорт и анализ данных.

Pandas MultiIndex.nlevels attribute returns the integer number of levels in the MultiIndex.

Syntax: MultiIndex.nlevels

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

# importing pandas as pd
import pandas as pd
  
# Creating the array
array = [[1, 2, 3], ["Sharon", "Nick", "Bailey"]]
  
# Print the array
print(array)

Выход :

Now let’s create the MultiIndex using this array

# Creating the MultiIndex
midx = pd.MultiIndex.from_arrays(array, names =("Number", "Names"))
  
# Print the MultiIndex
print(midx)

Выход :

Now we will find the number of levels in the MultiIndex.

# Print the number of the levels in MultiIndex
midx.nlevels

Output :

As we can see in the output, there are 2 levels in the midx MultiIndex.
 
Example #2: Use MultiIndex.nlevels attribute to find the number of levels in the given MultiIndex.

# importing pandas as pd
import pandas as pd
  
# Creating the array
array = [[1, 2, 3], ["Sharon", "Nick", "Bailey"],
            ["Doctor", "Scientist", "Physicist"]]
  
# Print the array
print(array)

Выход :

Now let’s create the MultiIndex using this array

# Creating the MultiIndex
midx = pd.MultiIndex.from_arrays(array, 
          names =("Ranking", "Names", "Profession"))
  
# Print the MultiIndex
print(midx)

Выход :

Now we will find the number of levels in the MultiIndex.

# Print the number of level in MultiIndex
midx.nlevels

Выход :

Как видно из вывода, midx MultiIndex имеет 3 уровня.

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.