2

With sed, I can do

$ sed 's/^/prefix/' <<EOF
> foo
> EOF
prefixfoo

When I use pandas.Series.str.replace, the regex does not work. The minimal working example

import pandas as pd

df = pd.DataFrame({"text": ["foo", "bar"]})
df.text.str.replace("^", "prefix", regex=True)

returns

0    foo
1    bar
Name: text, dtype: object

1 Answer 1

2

It works if you capture the ^:

df['text'].str.replace(r'(^)', 'prefix', regex=True)

Output:

0    prefixfoo
1    prefixbar
Name: text, dtype: object

That said the best method to prepend a string would be to concatenate:

'prefix'+df['text']
Sign up to request clarification or add additional context in comments.

3 Comments

regex=True is the default behavior of str.replace and we usually don't write it explicitly.
@Tim which pandas version are you using? This will change to False in a future release and currently raises a warning if you don't explicitly pass True
"FutureWarning: The default value of regex will change from True to False in a future version. In addition, single character regular expressions will *not be treated as literal strings when regex=True.*"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.