0

I have a pandas dataframe like the following:

Date   Title 
Jan 1  Washington Running
Jan 2  Jefferson City Cycling
Jan 3  Springfield Running
...

How can I remove the word "Running" or "Cycling" from all of the titles? I would like to get:

Date   Title 
Jan 1  Washington
Jan 2  Jefferson City
Jan 3  Springfield
...
0

1 Answer 1

2

You'll want to use pandas's string modifiers. Here are the docs for pandas.Series.str.replace(). It is slightly faster than the normal replace.

Mechanical_meat's great one line approach works with .str.replace() also:

df['Title'].str.replace(r'(\bRunning\b|\bCycling\b)','',regex=True)

I thought I'd offer the alternative of using df['Title'].str.replace('Running','') and df['Title'].str.replace('Cycling',''). Why do it in two steps? It avoids regex which can be "costly". Running a timeit on the two for small dataframes though finds the overhead of running replace twice is significantly higher than the cost of regex. I'd imagine it only gets worse for larger dataframes.

Sign up to request clarification or add additional context in comments.

Comments

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.