Pandas str.replace

I ran into a problem when using pandas str.replace on Series. I use pandas in a Jupyter notebook (although the result is the same as a regular python script).

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
+4
source share
1 answer

It works if you exit the pipe.

>>> df[0].str.replace(" \| ", "@")
0    abc@def
Name: 0, dtype: object

The function is str.replaceequivalent to 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 the appearance of the pattern / regular expression in Series / Index with another line. Equivalent to str.replace () or re.sub ().

+2
source

All Articles