[英]Replace part of string in a column with words in another column based on condition - python
I have a dataset with 3 columns.我有一个包含 3 列的数据集。
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?任何人都可以在 Python 中帮我解决这个问题吗? I have tried some things with the replace() function but it doesn't seem to be working.我用 replace() function 尝试了一些东西,但它似乎不起作用。 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!谢谢!
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勇敢是一个网站
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.