Python| Pandas Series.rename_axis()
Pandas 系列是带有轴标签的一维 ndarray。标签不必是唯一的,但必须是可散列的类型。该对象支持基于整数和基于标签的索引,并提供了许多用于执行涉及索引的操作的方法。
Pandas Series.rename_axis()
函数用于为索引或列设置轴的名称。
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
示例 #1:使用Series.rename_axis()
函数重命名给定 Series 对象的轴。
# 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)
输出 :
现在我们将使用Series.rename_axis()
函数来重命名给定系列对象的轴。
# rename the axis
result = sr.rename_axis('Beverages')
# Print the result
print(result)
输出 :
正如我们在输出中看到的, Series.rename_axis()
函数已成功重命名给定系列对象的轴。示例 #2:使用Series.rename_axis()
函数重命名给定 Series 对象的 MultiIndex 轴。
# 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)
输出 :
现在我们将使用Series.rename_axis()
函数来重命名给定系列对象的轴。
# 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)
输出 :
正如我们在输出中看到的, Series.rename_axis()
函数已成功重命名给定系列对象的轴的两个级别。