sha*_*ker 8 python numpy vectorization
Series.apply()使用输入对应(可以是字典,系列或函数)映射系列的值
调用Series的值的函数.可以是ufunc(适用于整个系列的NumPy函数)或仅适用于单个值的Python函数
apply()似乎它确实做了大部分事情map(),在应用矢量化操作时矢量化标量函数.同时map()允许对空值处理进行一定程度的控制.除了Python apply()和map()函数的历史类比之外,是否有理由在一般情况下更喜欢使用其中一个?为什么这些功能不能合并?
区别很微妙:
pandas.Series.map将用您传递给 的值替换 Series 的值map。
pandas.Series.apply将对Series 的值应用一个函数(可能带有参数)。
区别在于您可以传递给方法的内容
map和 都apply可以接收一个函数:s = pd.Series([1, 2, 3, 4])
def square(x):
return x**2
s.map(square)
0 1
1 2
2 3
3 4
dtype: int64
s.apply(square)
0 1
1 2
2 3
3 4
dtype: int64
Run Code Online (Sandbox Code Playgroud)
map不能有多个参数(它将输出 a ValueError):def power(x, p):
return x**p
s.apply(power, p=3)
0 1
1 8
2 27
3 64
dtype: int64
s.map(power,3)
---------------------------------------------------------------------------
ValueError
Run Code Online (Sandbox Code Playgroud)
map可以接收字典(甚至是字典,pd.Series在这种情况下它将使用索引作为键),而apply不能(它将输出 a TypeError)dic = {1: 5, 2: 4}
s.map(dic)
0 5.0
1 4.0
2 NaN
3 NaN
dtype: float64
s.apply(dic)
---------------------------------------------------------------------------
TypeError
s.map(s)
0 2.0
1 3.0
2 4.0
3 NaN
dtype: float64
s.apply(s)
---------------------------------------------------------------------------
TypeError
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1030 次 |
| 最近记录: |