我在系列上使用 pandas str.replace 时遇到问题。我在 Jupyter notebook 中使用 pandas(虽然结果与常规 python 脚本相同)。
import pandas as pd
s = ["abc | def"]
df = pd.DataFrame(data=s)
print(s[0].replace(" | ", "@"))
print(df[0].str.replace("| ", "@"))
print(df[0].map(lambda v: v.replace("| ", "@")))
Run Code Online (Sandbox Code Playgroud)
这是结果
ipython Untitled1.py
abc@def
0 @a@b@c@ @|@ @d@e@f@
Name: 0, dtype: object
0 abc @def
Name: 0, dtype: object
Run Code Online (Sandbox Code Playgroud)
如果您逃离管道,它会起作用。
>>> df[0].str.replace(" \| ", "@")
0 abc@def
Name: 0, dtype: object
Run Code Online (Sandbox Code Playgroud)
该str.replace函数等效于re.sub:
import re
>>> re.sub(' | ', '@', "abc | def")
'abc@|@def'
>>> "abc | def".replace(' | ', '@')
'abc@def'
Run Code Online (Sandbox Code Playgroud)
Series.str.replace(pat, repl, n=-1, case=True, flags=0):用其他字符串替换系列/索引中出现的模式/正则表达式。等效于 str.replace() 或 re.sub()。
| 归档时间: |
|
| 查看次数: |
8415 次 |
| 最近记录: |