python - Pandas Series.apply() 和 Series.map() 有什么区别?

标签 python numpy vectorization

这个问题在这里已经有了答案:





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将申请 功能 (可能带有参数)到系列的值。
区别在于您可以传递给方法的内容

  • 两者 mapapply可以接收一个函数:

  • 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/

    相关文章:

    python dask dataframe将元组列拆分为两列

    Python:从另一个类调用装饰器方法

    Python numpy where 函数与日期时间

    r - 非常大的字符矩阵循环的性能缩放

    python - 布伦特算法的矢量化版本(求根)

    python - 如何在numpy中按索引累积数组?

    python - 在 Python 中合并两个 CSV 文件

    python - 矩阵的总和,偶数或奇数

    python - Numpy 未安装,也 "Can' 在以下目录中找不到可用的 init.tcl :"

    python - 在 Ubuntu 12.04 上升级到 numpy 1.8.0