Replacing words in strings, if they match a word from a separate series

Viewed 47

I have a series that has nearly 4,000 different strings, along with a data frame with two series. I am trying to iterate through each string, find words that match in those strings to any of the words in the second series of the other data frame. If they match, then replace the word in the string, from the series, with the word from the first series in the data frame.

Here's an example of what I'm trying to do.

Example string that's split to a list.

0    [I, like, the, acura, vigor]

The data frame.


acura   integra
0   acura   legend
1   acura   vigor
2   acura   rlx
3   acura   ilx
4   acura   mdx

So, that string would replace 'vigor' with 'acura'.

[I, like, the, acura, acura]
2 Answers

Actually the dataframe approach seems a bit over engineered. I'd recommend to use simple regular expression:

import re

txt = 'this is a test text to replace legend, 2nd legend and fox with acura'
wordlist = ['fox', 'legend']
for word in wordlist:
    txt = re.sub(word,'acura',txt)

print(txt)

If you need the dataframe for further steps you can still use the regex example as a basis.

Let's break the problem down.

  1. You want to iterate over the list. For each word w in the list,
    1. Find the word w in the dataframe
    2. Set that index in the list to the corresponding replacement from the dataframe.

As code,

mylist = ['I', 'like', 'the', 'acura', 'vigor']
# df = the dataframe, with columns 'replacement' and 'lookup'
for index, word in enumerate(mylist):
    matched_row = df.loc[df['lookup'] == word]
    if not matched_row.empty:
        mylist[index] = matched_row.iloc[0]['replacement']
Related