![](/img/trans.png)
[英]Change a value of a column when it another column value is equal to one of the values from a list
[英]Remove values from one column, that are equal to the value in another
我目前有两列:
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使我们可以一次执行所有此类操作,而无需迭代。
您可以使用删除功能从列表中删除元素。
语法:list.remove(元素)
其中“列表”是您的句子列表,“元素”是您要删除的水果名称。
要了解有关删除功能的更多信息,请参阅python文档或以下链接: https : //www.programiz.com/python-programming/methods/list/remove
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.