[英]Python: Replace string in one column from list in other column
I need some help please.我需要一些帮助。
I have a dataframe with multiple columns where 2 are:我有一个包含多列的数据框,其中 2 是:
Content_Clean = Column filled with Content - String Content_Clean = 用内容填充的列 - 字符串
Removals: list of strings to be removed from Content_Clean Column删除:要从 Content_Clean 列中删除的字符串列表
Problem: I am trying to replace words in Content_Clean with spaces if in Removals Column: Example Image问题:如果在 Removals 列中,我试图用空格替换 Content_Clean 中的单词:示例图像
Example:例子:
Content Clean: 'Johnny and Mary went to the store'内容清洁:“约翰尼和玛丽去了商店”
Removals: ['Johnny','Mary']删除:['约翰尼','玛丽']
Output: 'and went to the store'输出:'然后去了商店'
Example Code:示例代码:
for i in data_eng['Removals']:
for u in i:
data_eng['Content_Clean_II'] = data_eng['Content_Clean'].str.replace(u,' ')
This does not work as Removals columns contain lists per row.这不起作用,因为移除列包含每行的列表。
Another Example:另一个例子:
data_eng['Content_Clean_II'] = data_eng['Content_Clean'].apply(lambda x: re.sub(data_eng.loc[data_eng['Content_Clean'] == x, 'Removals'].values[0], '', x))
Does not work as this code is only looking for one string.不起作用,因为此代码仅查找一个字符串。
The problem is that Removals column is a list that I want use to remove/ replace with spaces in the Content_Clean column on a per row basis.问题是 Removals 列是一个列表,我想用它来逐行删除/替换 Content_Clean 列中的空格。
The example image link might help示例图片链接可能会有所帮助
Here you go.干得好。 This worked on my test data.
这适用于我的测试数据。 Let me know if it works for you
请让我知道这对你有没有用
def repl(row):
for word in row['Removals']:
row['Content_Clean'] = row['Content_Clean'].replace(word, '')
return row
data_eng = data_eng.apply(repl, axis=1)
You can call the str.replace(old, new) method to remove unwanted words from a string.您可以调用str.replace(old, new)方法从字符串中删除不需要的单词。 Here is one small example I have done.
这是我做过的一个小例子。
a_string = "I do not like to eat apples and watermelons"
stripped_string = a_string.replace(" do not", "")
print(stripped_string)
This will remove "do not" from the sentence这将从句子中删除“不要”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.