Dat*_*ars 2 python series python-3.x pandas
双方pandas.Series.map并pandas.Series.replace似乎给了相同的结果。是否有理由使用一个而不是另一个?例如:
import pandas as pd
df = pd.Series(['Yes', 'No'])
df
0 Yes
1 No
dtype: object
Run Code Online (Sandbox Code Playgroud)
df.replace(to_replace=['Yes', 'No'], value=[True, False])
0 True
1 False
dtype: bool
Run Code Online (Sandbox Code Playgroud)
df.map({'Yes':True, 'No':False})
0 True
1 False
dtype: bool
Run Code Online (Sandbox Code Playgroud)
df.replace(to_replace=['Yes', 'No'], value=[True, False]).equals(df.map({'Yes':True, 'No':False}))
True
Run Code Online (Sandbox Code Playgroud)
这两种方法都用于替换值。
从Series.replace文档:
用值替换 to_replace 中给出的值。
从Series.map文档:
用于将 Series 中的每个值替换为另一个值,该值可能来自函数、dict 或 Series。
它们的区别如下:
replace接受 str、regex、list、dict、Series、int、float 或 None。
map接受一个 dict 或一个系列。replacere.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
Run Code Online (Sandbox Code Playgroud)
正如您在
s.map方法中看到的那样,字典中找不到的值将转换为 NaN,除非字典具有默认值(例如 defaultdict)
对于
s.replace,它只是替换要替换的值,其余部分保持原样。
| 归档时间: |
|
| 查看次数: |
876 次 |
| 最近记录: |