📅  最后修改于: 2023-12-03 15:03:28.537000             🧑  作者: Mango
Pandas Series.map()用于执行指定函数或映射到Series中的所有元素
Series.map(arg, na_action=None)
返回一个新的Series,其中包含应用于原始Series的映射函数或字典的结果。
import pandas as pd
fruits = pd.Series(['apple', 'banana', 'mango', 'grape'])
fruits_uppercase = fruits.map(lambda x: x.upper())
print(fruits_uppercase)
输出:
0 APPLE
1 BANANA
2 MANGO
3 GRAPE
dtype: object
import pandas as pd
fruits = pd.Series(['apple', 'banana', 'mango', 'grape'])
dict_fruits = {'apple': 'red', 'banana': 'yellow', 'mango': 'orange', 'grape': 'purple'}
color_fruit = fruits.map(dict_fruits)
print(color_fruit)
输出:
0 red
1 yellow
2 orange
3 purple
dtype: object
import pandas as pd
import numpy as np
fruits = pd.Series(['apple', 'banana', np.nan, 'grape'])
upper_fruits = fruits.map(lambda x: x.upper(), na_action='ignore')
print(upper_fruits)
输出:
0 APPLE
1 BANANA
2 NaN
3 GRAPE
dtype: object
Pandas Series.map()方法可以轻松地对Series对象应用映射函数,应用方法非常灵活,可以直接传递函数也可以传递字典进行映射。同时,也可以处理缺失值。