我目前有两列:
Word Sentence
apple [this, fruit, is, an, apple]
orange [orange, is, this, fruit]
grape [this, is, grape]
strawberry [strawberry, is, nice]
我如何从df ['Sentence']中删除df ['Word']中出现的值,以便输出为:
Word Sentence
apple [this, fruit, is, an]
orange [is, this, fruit]
grape [this, is]
strawberry [is, nice]
我目前正在尝试使用这个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
但是,循环不会删除值。实现所需输出的最佳方法是什么?
怎么样......
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允许我们一次执行这样的操作,不需要迭代。
您可以使用remove函数从列表中删除元素。
语法:list.remove(element)
'list'是你的句子列表,'element'是你要删除的水果名称。
要了解有关删除函数的更多信息,请参阅python docs或此链接:https://www.programiz.com/python-programming/methods/list/remove