从一列中删除与另一列中的值相等的值

2024-03-29 05:14:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前有两个专栏:

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

但是,循环并没有删除这些值。达到预期输出的最佳方法是什么


Tags: anappledfisthissentencewordnice
2条回答

像这样的怎么样

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文档或以下链接:https://www.programiz.com/python-programming/methods/list/remove

相关问题 更多 >