簡體   English   中英

Python根據變量較少的另一個DataFrame從DataFrame刪除行

[英]Python delete row from a DataFrame based on another DataFrame with less variables

我有這樣的df1:

id 1  2  3  4  5
0  1  1  0  0  0 
1  1  0  1  0  0
2  1  0  0  0  1

我的df(較少的列,較少的情況)具有以下值:

id 1  2  5  
0  1  1  0
1  1  0  1

我想從df1中刪除與df2具有相同值的行,因此最終df如下所示:

id 1  2  3  4  5
1  1  0  1  0  0

我要刪除2行,因為df1和df2在其相應列上共享相同的值。

謝謝!

這將解決您的問題:

print (pd.merge(df1,df2, indicator=True, how='outer')
         .query('_merge=="left_only"')
         .drop('_merge', axis=1))

希望這可以幫助您找到解決方案。 df2是一個數據幀,其中其他兩個的交集基於三個相同的列。 cleared_df是除交集之外的初始df

#Replicating the question's input
d={1:[1,1,1],2:[1,0,0],3:[0,1,0],4:[0,0,0],5:[0,0,1]}
d1={1:[1,1],2:[1,0],5:[0,1]}
df = pd.DataFrame(data=d)
df1 = pd.DataFrame(data=d1)
#Make df with the same records on 1,2,5
df2=pd.merge(df, df1, on=[1,2,5], how='inner')
#Concat the initial df with the one with the same records, then drop the duplicates
cleared_df=pd.concat([df, df2]).drop_duplicates(keep=False)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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