[英]Pandas compare two dataframes and remove what matches in one column
我有兩個獨立的pandas數據幀( df1
和df2
),它們有多個列,但只有一個是共同的('text')。
我想在df2
中找到df2
和df1
共有的任何行中沒有匹配項的每一行。
DF1
A B text
45 2 score
33 5 miss
20 1 score
DF2
C D text
.5 2 shot
.3 2 shot
.3 1 miss
結果df(刪除包含未命中的行,因為它出現在df1中)
C D text
.5 2 shot
.3 2 shot
在這種情況下是否可以使用isin
方法?
正如您所問,您可以使用isin
有效地執行此操作(無需借助昂貴的merge
)。
>>> df2[~df2.text.isin(df1.text.values)]
C D text
0 0.5 2 shot
1 0.3 2 shot
編輯:
import numpy as np
mergeddf = pd.merge(df2,df1, how="left")
result = mergeddf[(np.isnan(mergeddf['A']))][['C','D','text']]
您可以合並它們並僅保留具有NaN的行。
df2[pd.merge(df1, df2, how='outer').isnull().any(axis=1)]
或者你可以使用isin
:
df2[~df2.text.isin(df1.text)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.