【问题标题】:Is there a difference between `Series.replace()` and `Series.map()` in pandas? [duplicate]pandas 中的 `Series.replace()` 和 `Series.map()` 有区别吗? [复制]
【发布时间】:2020-11-06 20:46:01
【问题描述】:

pandas.Series.mappandas.Series.replace 似乎都给出了相同的结果。有理由使用其中一个吗?例如:

import pandas as pd
df = pd.Series(['Yes', 'No'])
df

0    Yes
1     No
dtype: object
df.replace(to_replace=['Yes', 'No'], value=[True, False])

0     True
1    False
dtype: bool
df.map({'Yes':True, 'No':False})

0     True
1    False
dtype: bool
df.replace(to_replace=['Yes', 'No'], value=[True, False]).equals(df.map({'Yes':True, 'No':False}))

True

【问题讨论】:

    标签: python python-3.x pandas series


    【解决方案1】:

    这两种方法都用于替换值。

    来自Series.replace docs:

    将 to_replace 中给定的值替换为 value。

    来自Series.map docs:

    用于将 Series 中的每个值替换为另一个值,该值可能源自函数、dict 或 Series。

    它们的区别如下:

    1. replace 接受 str、regex、list、dict、Series、int、float 或 None。 map 接受 dict 或 Series。
    2. 它们在处理空值方面有所不同。
    3. replace 在后台使用 re.sub。替换 re.sub 的规则是相同的。

    举个例子:

    In [124]: s = pd.Series([0, 1, 2, 3, 4])    
    In [125]: s
    Out[125]: 
    0    0
    1    1
    2    2
    3    3
    4    4
    dtype: int64
    
    In [126]: s.replace({0: 5})
    Out[126]: 
    0    5
    1    1
    2    2
    3    3
    4    4
    dtype: int64
    
    In [129]: s.map({0: 'kitten', 1: 'puppy'}) 
    Out[129]: 
    0    kitten
    1     puppy
    2       NaN
    3       NaN
    4       NaN
    dtype: object
    

    正如您在s.map 方法中看到的那样,在字典中找不到的值将被转换为 NaN,除非字典具有默认值(例如 defaultdict)

    对于s.replace,它只是替换要替换的值,保持其余部分不变。

    【讨论】:

    • 感谢您指出区分这两种方法的细节。
    猜你喜欢
    • 2016-11-11
    • 2019-10-30
    • 2020-12-20
    • 2014-09-24
    • 2017-05-31
    • 2013-05-28
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    相关资源
    最近更新 更多