Pandas 系列是带有轴标签的一维ndarray。标签不必是唯一的,但必须是可哈希的类型。该对象同时支持基于整数和基于标签的索引,并提供了许多方法来执行涉及索引的操作。
Pandas Series.set_axis()功能用于将所需的索引分配给给定轴。可以通过分配list-like或索引来更改列标签或行标签的索引。
用法: Series.set_axis(labels, axis=0, inplace=None)
参数:
labels:新索引的值。
axis:要更新的轴。值0标识行,值1标识列。
inplace:是否返回新的%(klass)s实例。
返回:重命名:系列
范例1:采用Series.set_axis()函数重置给定Series对象的轴。
# importing pandas as pd
import pandas as pd
# Creating the Series
sr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow'])
# Create the Index
index_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5', 'City 6']
# set the index
sr.index = index_
# Print the series
print(sr)
输出:
现在我们将使用Series.set_axis()函数重置给定系列对象的索引
# Create the Index
didx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W',
periods = 6, tz = 'Europe/Berlin')
# reset the index
sr.set_axis(didx, inplace = True)
# Print the series
print(sr)
输出:
正如我们在输出中看到的,Series.set_axis()函数已成功重置给定Series对象的索引。
范例2:采用Series.set_axis()函数重置给定Series对象的轴。
# importing pandas as pd
import pandas as pd
# Creating the Series
sr = pd.Series([100, 25, 32, 118, 24, 65])
# Print the series
print(sr)
输出:
现在我们将使用Series.set_axis()函数重置给定系列对象的索引
# Assign the new index
sr.set_axis(['A', 'B', 'C', 'D', 'E', 'F'], inplace = True)
# print the series
print(sr)
输出:
正如我们在输出中看到的,Series.set_axis()函数已成功重置给定Series对象的索引。