6

I have a DataFrame called "Animals" that looks like this:

 Words
 The Black Cat
 The Red Dog

I want to add a plus sign before each word so that it looks like this:

 Words
 +The +Black +Cat
 +The +Red +Dog

I have tried this using regex but it did not work:

 df = re.sub(r'([a-z]+)', r'+\1', Animals)

1 Answer 1

7

You can use str.replace with the following regex to make the change to all rows of the column:

df.Words = df.Words.str.replace(r'(\b\S)', r'+\1')

The DataFrame then looks like this:

>>> df
              Words
0  +The +Black +Cat
1    +The +Red +Dog
Sign up to request clarification or add additional context in comments.

2 Comments

Very good, thank for for the solution. I know not part of the original question but was wondering whether this could also be adapted to remove white space between words?
@user3682157: no problem, glad it helped. To remove all of the whitespace you could perhaps use df.Words.str.replace(r'\s', r'').

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.