Python | Панды MultiIndex.swaplevel ()

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

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

Pandas MultiIndex.swaplevel() function is used to swap levels of the MultiIndex. It swap level i with level j. Calling this method does not change the ordering of the values.

Syntax: MultiIndex.swaplevel(i=-2, j=-1)

Parameters :
i : First level of index to be swapped. Can pass level name as string. Type of parameters can be mixed.
j : Second level of index to be swapped. Can pass level name as string. Type of parameters can be mixed.

Returns : A new MultiIndex

Example #1: Use MultiIndex.swaplevel() function to swap the 0th level with the 1st level of the MultiIndex.

# importing pandas as pd
import pandas as pd
  
# Create the MultiIndex
midx = pd.MultiIndex.from_arrays([["Networking", "Cryptography"
                                     "Anthropology", "Science"], 
                                             [88, 84, 98, 95]])
  
# Print the MultiIndex
print(midx)

Выход :

Now let’s swap the 0th level with the 1st level of the MultiIndex.

# swap the levels
midx.swaplevel(0, 1)

Output :

As we can see in the output, the function has swapped the 0th level with the 1st level of the MultiIndex.
 
Example #2: Use MultiIndex.swaplevel() function to swap the 0th level with the 1st level of the MultiIndex.

# importing pandas as pd
import pandas as pd
  
# Create the MultiIndex
midx = pd.MultiIndex.from_arrays([["Beagle", "Sephard", "Labrador", "Retriever"],
                                       [8, 4, 11, 3], ["A1", "B1", "A2", "C1"]])
  
# Print the MultiIndex
print(midx)

Выход :

Now let’s swap the 0th level with the 2nd level of the MultiIndex.

# swap the levels
midx.swaplevel(0, 2)

Выход :

Как видно из выходных данных, функция поменяла местами 0-й уровень на 2-й уровень MultiIndex.

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

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