Pandas str.replace 管道字符不起作用?
Pandas str.replace of pipe character not working?
我在系列中使用 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("| ", "@")))
这是结果
ipython Untitled1.py
abc@def
0 @a@b@c@ @|@ @d@e@f@
Name: 0, dtype: object
0 abc @def
Name: 0, dtype: object
如果你逃离管道,它会起作用。
>>> df[0].str.replace(" \| ", "@")
0 abc@def
Name: 0, dtype: object
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()
.
我在系列中使用 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("| ", "@")))
这是结果
ipython Untitled1.py
abc@def
0 @a@b@c@ @|@ @d@e@f@
Name: 0, dtype: object
0 abc @def
Name: 0, dtype: object
如果你逃离管道,它会起作用。
>>> df[0].str.replace(" \| ", "@")
0 abc@def
Name: 0, dtype: object
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 tostr.replace()
orre.sub()
.