HOWTO · Pandas
Pandas map()
本教程解釋了我們如何使用 Series.map()方法將 Pandas Series 的值替換為另一個值。
本頁內容
Series.map() 會轉換 pandas Series 中的每個值,並回傳新的 Series。回傳物件會保留輸入索引,因此對應操作改變的是值,而非索引標籤。你可以傳入函式、類字典查找表或另一個 Series;完整 API 說明請參閱 Series.map() 參考文件。
Series.map() 如何轉換值
引數會決定每個輸入值如何轉換。可呼叫物件會接收每個值;字典會以輸入值作為鍵;對應用的 Series 則會以其索引作為查找鍵,並以其值作為替換結果。即使查找結果為缺值,回傳結果仍會保留被對應的 Series 索引,讓對應後的值能與原始資料列對齊。呼叫此方法不會修改輸入的 Series;請儲存回傳值,或將它指派到需要轉換資料的位置。結果的資料型別取決於對應後的值,因此查找引入缺值或回傳字串時,結果型別可能與輸入不同。
以函式、字典或 Series 作為對應方式
需要套用規則時使用可呼叫物件;需要固定查找表時使用字典;若對應表已儲存為具標籤的資料,則可使用 Series。字典中沒有對應項目的鍵會得到缺值。使用對應用的 Series 時,請比對其索引,而不是其值。
使用 na_action 處理缺值
預設情況下,可呼叫物件也會套用至缺值;若操作會呼叫 .upper() 之類的方法,這可能不合適。設定 na_action="ignore",即可在對應其他值時保留輸入中的缺值。這個選項不會移除缺值所在的資料列。若某個輸入值在字典或 Series 對應表中找不到對應項目,也會變成缺值,即使該輸入值本身並非缺值。
對應 DataFrame 欄位
從 DataFrame 選取單一欄會回傳 Series,因此你可以對該欄呼叫 map(),再將回傳的 Series 指派回去。其他欄位會維持原樣。指派時會依索引對齊,因此回傳的 Series 會保留所選欄位的資料列標籤。
執行並驗證範例
執行這個自包含範例前,請先在 Python 環境中安裝 pandas。範例會列印各種對應結果,方便你在本機檢視值與索引。下方是這段程式碼的擷取結果;程式碼與輸出區塊中的顯示標籤維持英文。
執行此範例:
本節中的程式碼以及顯示的標籤或輸出仍為英文。
import pandas as pd
scores = pd.Series([85, 87, 90], index=["a", "b", "c"])
print("Callable:")
print(scores.map(lambda value: value + 5))
labels = {85: "pass", 90: "excellent"}
print("Dictionary:")
print(scores.map(labels))
label_table = pd.Series({85: "pass", 87: "review", 90: "excellent"})
print("Series lookup:")
print(scores.map(label_table))
names = pd.Series(["ada", pd.NA, "lin"])
print("Ignore missing values:")
print(names.map(lambda value: value.upper(), na_action="ignore"))
table = pd.DataFrame({"score": [85, 90], "student": ["Ada", "Lin"]}, index=["a", "b"])
table["grade"] = table["score"].map({85: "pass", 90: "excellent"})
print("Mapped DataFrame column:")
print(table)
Callable:
a 90
b 92
c 95
dtype: int64
Dictionary:
a pass
b NaN
c excellent
dtype: str
Series lookup:
a pass
b review
c excellent
dtype: str
Ignore missing values:
0 ADA
1 NaN
2 LIN
dtype: str
Mapped DataFrame column:
score student grade
a 85 Ada pass
b 90 Lin excellent