python – Pandas str.replace

我在系列上使用pandas str.replace时遇到了一个问题.我在Jupyter笔记本中使用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().

点赞