Python基于另一个具有较少变量的DataFrame从DataFrame中删除行

问题描述 投票:0回答:2

我有这样的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共享相同值的行,所以final df如下所示:

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

我正在删除2行,因为df1和df2在相应的列上共享相同的值。

谢谢!

python python-3.x pandas numpy dataframe
2个回答
1
投票

这将解决您的问题:

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

0
投票

我希望这可以帮助您找到解决方案。 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)
© www.soinside.com 2019 - 2024. All rights reserved.