Pandas 字符串替换

Fla*_*ert 6 python pandas

我在系列上使用 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)

Ale*_*der 5

如果您逃离管道,它会起作用。

>>> 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()。