簡體   English   中英

從一列中刪除等於另一列中的值的值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM