[英]Remove values from one column, that are equal to the value in another
I currently have two columns: 我目前有两列:
Word Sentence
apple [this, fruit, is, an, apple]
orange [orange, is, this, fruit]
grape [this, is, grape]
strawberry [strawberry, is, nice]
How would I go about removing the value that appears in df['Word'] from df['Sentence'] so that the output would be: 我将如何从df ['Sentence']中删除df ['Word']中出现的值,以便输出为:
Word Sentence
apple [this, fruit, is, an]
orange [is, this, fruit]
grape [this, is]
strawberry [is, nice]
I am currently trying to use this while loop, which is not very pythonic. 我目前正在尝试使用while循环,这不是pythonic。
count_row = df.shape[0]
i=0
while i < count_row :
mylist = df.iloc[i]["Sentence"]
mykeyword = df.iloc[i]["Word"]
mylist = mylist.split()
for word in mylist:
if word == mykeyword:
df.iloc[i]["Sentence"] = df.iloc[i]["Sentence"].replace(word, '')
print(i)
i=i+1
However, the loop is not removing the values. 但是,循环不会删除这些值。 What is the best way to achieve the desired output?
实现所需输出的最佳方法是什么?
How about something like... 怎么样...
def remove_name(r):
r['Sentence'] = [w for w in r['Sentence'] if w != r['Word']]
return r
df.apply(remove_name,axis=1)
Apply lets us perform operations like this all at once, no iterations required. Apply使我们可以一次执行所有此类操作,而无需迭代。
You can use remove function to remove an element from a list. 您可以使用删除功能从列表中删除元素。
Syntax: list.remove(element) 语法:list.remove(元素)
Where 'list' is your sentence list and 'element' is your fruit name to be removed. 其中“列表”是您的句子列表,“元素”是您要删除的水果名称。
To know more about remove function refer python docs or this link: https://www.programiz.com/python-programming/methods/list/remove 要了解有关删除功能的更多信息,请参阅python文档或以下链接: https : //www.programiz.com/python-programming/methods/list/remove
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.