这个问题在这里已经有了答案:
Difference between map, applymap and apply methods in Pandas
(11 个回答)
去年关闭。
Series.map() :
Map values of Series using input correspondence (which can be a dict, Series, or function)
Series.apply()
Invoke function on values of Series. Can be ufunc (a NumPy function that applies to the entire Series) or a Python function that only works on single values
apply()
似乎它几乎可以做所有事情 map()
确实如此,在按原样应用矢量化操作的同时矢量化标量函数。同时map()
允许对空值处理进行一定程度的控制。除了与 Python 的 apply()
的历史类比之外和 map()
功能,是否有理由在一般用途中更喜欢一种?为什么不把这些功能结合起来呢?
最佳答案
区别很微妙:pandas.Series.map
将用您传递给 map
的值替换 Series 的值.pandas.Series.apply
将申请 功能 (可能带有参数)到系列的值。
区别在于您可以传递给方法的内容
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
map
不能有多个参数(它会输出一个 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
map
可以接收字典(甚至 pd.Series
在这种情况下它将使用索引作为键)而 apply
不能(它会输出 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
关于python - Pandas Series.apply() 和 Series.map() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38276860/