如何为 Pandas 系列索引标签添加后缀?


add_suffix 是 Pandas Series 函数,用于为系列索引标签添加字符串后缀。此方法将返回一个具有更新标签的新系列对象。

此 add_suffix 方法将字符串作为参数,并使用该字符串更新系列标签。它将在系列的索引标签后添加给定的字符串。

示例

# import pandas package
import pandas as pd

# create a pandas series
s = pd.Series([2,4,6,8,10])
print(series)

result = s.add_suffix('_Index')
print("Resultant series with updated labels: ", result)

解释

在以下示例中,我们使用 Python 列表创建了一个系列对象“s”,并且我们没有为此系列对象定义索引标签。Pandas Series 构造函数将自动分配从 0 到 4 的索引值。

通过使用此 add_suffix 方法,我们可以更改系列对象“s”的标签。

输出

0   1
1   3
2   5
3   7
4   9
dtype: int64

Resultant series with updated labels:
0_Index   2
1_Index   4
2_Index   6
3_Index   8
4_Index  10
dtype: int64

索引表示为 0-4 的系列是实际系列,而索引以“_Index”结尾的系列是 s.add_suffix 方法的结果系列。

示例

import pandas as pd

sr = pd.Series({'A':3,'B':5,'C':1})

print(sr)

# add suffix
result = sr.add_suffix('_Lable')

print('Resultant series with updated labels: ',result)

解释

“_Label”是在系列对象的 add_suffix 函数中作为参数给出的字符串,它将返回一个具有新索引标签的新 Pandas 系列对象。

输出

A   3
B   5
C   1
dtype: int64

Resultant series with updated labels:
A_Lable   3
B_Lable   5
C_Lable   1
dtype: int64

此代码块包含两个 Pandas 系列对象,第一个是实际的系列对象,最后一个系列对象是 add_suffix 方法的输出。add_suffix 方法已将索引标签从 A、B、C 更新为 A_Lable、B_Lable、C_Lable。

更新于: 2021年11月18日

406 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.