>>> s = pd.Series(['cat', 'dog', np.nan, 'rabbit'])>>> s
0cat1 dog
2 NaN
3 rabbit
dtype: object
根据字典值做映射,如果值不在字典里,会转换成NaN
>>> s.map({'cat':'kitten', 'dog':'puppy'})0 kitten
1 puppy
2 NaN
3 NaN
dtype: object
也接受函数作为入参,Series的每一个元素作为函数的入参
>>> s.map('I am a {}'.format)0 I am a cat1 I am a dog
2 I am a nan
3 I am a rabbit
dtype: object
防止缺失值的运算,可以使用na_action=‘ignore’
>>> s.map('I am a {}'.format, na_action='ignore')0 I am a cat1 I am a dog
2 NaN
3 I am a rabbit
dtype: object
2、apply
创建Series
>>> s = pd.Series([20,21,12], index=['London','New York','Helsinki'])>>> s
London 20
New York 21
Helsinki 12
dtype: int64
接受一个匿名函数,Series的元素作为函数的入参
>>> s.apply(lambda x: x ** 2)
London 400
New York 441
Helsinki 144
dtype: int64
apply入参除接受函数外,还接受额外的位置参数
>>> def subtract_custom_value(x, custom_value):
... return x - custom_value
>>> s.apply(subtract_custom_value, args=(5,))
London 15
New York 16
Helsinki 7
dtype: int64
还可以传递关键字参数
>>> def add_custom_values(x, **kwargs):
... formonthin kwargs:
... x += kwargs[month]... return x
>>> s.apply(add_custom_values, june=30, july=20, august=25)
London 95
New York 96
Helsinki 87
dtype: int64