如何為 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。
廣告