Pandas 字符串替换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36587559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas str.replace
提问by Flavien Lambert
I am facing an issue in using pandas str.replace on Series. I am using pandas in Jupyter notebook (although the result is the same with regular python script).
我在系列上使用 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("| ", "@")))
Here is the result
这是结果
ipython Untitled1.py
abc@def
0 @a@b@c@ @|@ @d@e@f@
Name: 0, dtype: object
0 abc @def
Name: 0, dtype: object
采纳答案by Alexander
It works if you escape the pipe.
如果您逃离管道,它会起作用。
>>> df[0].str.replace(" \| ", "@")
0 abc@def
Name: 0, dtype: object
The str.replacefunction is equivalent to re.sub:
该str.replace函数等效于re.sub:
import re
>>> re.sub(' | ', '@', "abc | def")
'abc@|@def'
>>> "abc | def".replace(' | ', '@')
'abc@def'
Series.str.replace(pat, repl, n=-1, case=True, flags=0): Replace occurrences of pattern/regex in the Series/Index with some other string. Equivalent to str.replace() or re.sub().
Series.str.replace(pat, repl, n=-1, case=True, flags=0):用其他字符串替换系列/索引中出现的模式/正则表达式。等效于 str.replace() 或 re.sub()。

