如何在 Pandas Series 的標籤前新增字首?
在 Pandas Series 的功能中,我們有一個名為 add_prefix 的函式,用於在標籤前新增字串字首。特別是在 Pandas Series 中,行標籤將以字串作為字首。
add_prefix 方法將返回一個帶有字首標籤的新 Series 物件。它將在 Series 的行標籤前新增給定的字串。
示例
import pandas as pd
series = pd.Series(range(1,10,2))
print(series)
# add Index_ prefix to the series labels
result = series.add_prefix('Index_')
print("Prefixed Series object with a string: ", result)解釋
在以下示例中,我們使用 Python range 函式建立了一個 Pandas Series,並且此 Series 物件的索引標籤是 0 到 4 之間的自動建立值。並且這些索引值使用 add_prefix 方法更新為字串字首“Index_”。
輸出
0 1 1 3 2 5 3 7 4 9 dtype: int64 Prefixed Series object with a string: Index_0 1 Index_1 3 Index_2 5 Index_3 7 Index_4 9 dtype: int64
此輸出塊顯示了兩個 Series 物件,上面的那個是初始的沒有字串字首的 Series,另一個是使用字串字首更新了索引標籤的 Series。
示例
import pandas as pd
sr = pd.Series({'a':1,'b':2,'c':3})
print(sr)
# add prefix
result = sr.add_prefix('Lable_')
print(result)解釋
這是 Pandas series.add_prefix 方法的另一個示例,初始 Series 物件是由一個帶有命名標籤(a、b、c)的 Python 字典建立的。
輸出
a 1 b 2 c 3 dtype: int64 Lable_a 1 Lable_b 2 Lable_c 3 dtype: int64
我們透過在原始索引標籤前新增字串“Lable_”來更新命名索引標籤。結果 Series 物件可以在上面的輸出塊中看到。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP