Python | Серия панд.rename_axis ()

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

Серия Pandas - это одномерный массив ndarray с метками осей. Этикетки не обязательно должны быть уникальными, но должны быть хешируемого типа. Объект поддерживает индексирование как на основе целых чисел, так и на основе меток и предоставляет множество методов для выполнения операций, связанных с индексом.

Pandas Series.rename_axis() function is used to set the name of the axis for the index or columns.

Syntax: Series.rename_axis(mapper=None, index=None, columns=None, axis=None, copy=True, inplace=False)

Parameter :
mapper : Value to set the axis name attribute.
index, columns : A scalar, list-like, dict-like or functions transformations to apply to that axis’ values.
axis : The axis to rename.
copy : Also copy underlying data.
inplace : Modifies the object directly, instead of creating a new Series or DataFrame.

Returns : Series, DataFrame, or None

Example #1: Use Series.rename_axis() function to rename the axis of the given Series object.

# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series([10, 25, 3, 11, 24, 6])
  
# Create the Index
index_ = ["Coca Cola", "Sprite", "Coke", "Fanta", "Dew", "ThumbsUp"]
  
# set the index
sr.index = index_
  
# Print the series
print(sr)

Выход :

Now we will use Series.rename_axis() function to rename the axis of the given series object.

# rename the axis
result = sr.rename_axis("Beverages")
  
# Print the result
print(result)

Выход :


As we can see in the output, the Series.rename_axis() function has successfully renamed the axis of the given series object.
 
Example #2 : Use Series.rename_axis() function to rename the MultiIndex axis of the given Series object.

# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series(["New York", "Chicago", "Toronto", "Lisbon", "Rio"])
  
# Create the MultiIndex
index_ = pd.MultiIndex.from_product([["Names"], ["City 1", "City 2", "City 3", "City 4", "City 5"]],
                                                                     names =["Level 1", "Level 2"])
  
# set the index
sr.index = index_
  
# Print the series
print(sr)

Выход :

Now we will use Series.rename_axis() function to rename the axis of the given series object.

# rename both the levels of the axis of 
# the given series object
result = sr.rename_axis(["First_level", "Second_level"])
  
# Print the result
print(result)

Output :

As we can see in the output, the Series.rename_axis() function has successfully renamed both the levels of the axis of the given series object.

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

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