简体   繁体   English

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

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

I have a dataset with 3 columns.我有一个包含 3 列的数据集。

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 -

Output 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.

相关问题 根据条件从另一个 dataframe 值替换列的值 - Python - Replace values of a column from another dataframe values based on a condition - Python 根据python中另一列的条件增加一列 - Increment a column based on the condition of another column in python 如何根据条件替换熊猫列中的字符串? - How to replace a string in pandas column based on a condition? 替换Python或Pandas中的一部分字符串(列名)? - Replace part of a string (column name) in Python or Pandas? 根据条件将列值替换为另一个表中的列值? - Replace column value with column value in another table based on condition? 如何用条件 pandas python 替换另一列中的列的值 - how to replace the values of a column from another column with condition pandas python 根据其他列条件用数据框中的另一个列表替换列表 - Replace list with another list in dataframe based on another column condition Python / pandas - 根据另一列中的单词在列中添加单词 - Python/pandas - Add word in column based on words in another column Pandas:根据字符串的一部分是否在另一列中的任何位置创建新列 - Pandas: Creating a new column based on if part of a string is anywhere in another column 如何根据python中其他列的条件将字符串列拆分为另一个列? - How to split a string column into another one based on condition of other column in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM