pandas.map()用於映射來自同一列的兩個係列的值。為了映射兩個係列,第一個係列的最後一列應與第二個係列的索引列相同,並且值也應唯一。
用法:
Series.map(arg, na_action=None)
參數:
arg:function, dict, or Series
na_action:{None, ‘ignore’} If ‘ignore’, propagate NA values, without passing them to the mapping correspondence. na_action checks the NA value and ignores it while mapping in case of ‘ignore’
返回類型:
Pandas Series with same as index as caller
範例1:
在下麵的示例中,兩個序列由相同的數據組成。 pokemon_names列和pokemon_types索引列相同,因此Pandas.map()與其餘兩列匹配並返回一個新係列。
Note:
-> 2nd column of caller of map function must be same as index column of passed series.
-> The values of common column must be unique too.
import pandas as pd
#reading csv files
pokemon_names = pd.read_csv("pokemon.csv", usecols = ["Pokemon"],
squeeze = True)
#usecol is used to use selected columns
#index_col is used to make passed column as index
pokemon_types = pd.read_csv("pokemon.csv", index_col = "Pokemon",
squeeze = True)
#using pandas map function
new=pokemon_names.map(pokemon_types)
print (new)
輸出:
範例2:
此函數僅適用於Series。傳遞數據幀將導致屬性錯誤。傳遞不同長度的序列將使輸出序列的長度與調用者相同。
相關用法
注:本文由純淨天空篩選整理自Kartikaybhutani大神的英文原創作品 Python | pandas.map()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。