Replace part of string in a column with words in another column based on condition - python

Viewed 42

I have a dataset with 3 columns.

Dataset

I need to lookup the entire word in "word" column in the "sentence" column and replace it with the entire word in the "replacement" column. No need to create a separate column for the replaced sentence.

I am expecting an output like this -

Output

Can anyone please help me with this in Python? I have tried some things with the replace() function but it doesn't seem to be working. This is what I tried -

new_col = []
for s in df["sentence"]:
    for index, w in enumerate(df["word"]):
        if w in s:
            a = ". ".join([s.replace(w, syno) for syno in df["replacement"][index]])
    new_col.append(a)

df["new_col"] = new_col

Thanks!

1 Answers

here is a working example :

sentence = "Google is a website"
before = "Google"
after = "Brave"

sentence = sentence.replace(before, after)
print(sentence)

Brave is a website

Related