繁体   English   中英

根据条件将一列中的部分字符串替换为另一列中的单词 - python

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

我有一个包含 3 列的数据集。

数据集

我需要在“句子”列的“单词”列中查找整个单词,并将其替换为“替换”列中的整个单词。 无需为替换的句子创建单独的列。

我期待这样的 output -

Output

任何人都可以在 Python 中帮我解决这个问题吗? 我用 replace() function 尝试了一些东西,但它似乎不起作用。 这就是我尝试过的 -

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

谢谢!

这是一个工作示例:

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

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

勇敢是一个网站

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM