大熊猫左外连接排除
问题描述:
我有2个大熊猫dataframes大熊猫左外连接排除
df1 = pd.DataFrame(data = {'col1' : ['finance', 'finance', 'finance', 'accounting', 'IT'], 'col2' : ['az', 'bh', '', '', '']})
df2 = pd.DataFrame(data = {'col1' : ['finance', 'finance', 'finance', 'finance', 'finance'], 'col2' : ['', 'az', '', '', '']})
DF1
col1 col2
0 finance az
1 finance bh
2 finance
3 accounting
4 IT
DF2
col1 col2
0 finance
1 finance az
2 finance
3 finance
4 finance
正如你所看到的数据帧中有空白值,以及。我尝试使用example,并没有给我我想要的结果。
common = df1.merge(df2,on=['col1','col2'])
df3=df1[(~df1.col1.isin(common.col1))&(~df1.col2.isin(common.col2))]
我想输出像
col1 col2
3 accounting
4 IT
答
失败的原因是你独立的比赛中col1
& col2
检查,并排除在任何一场比赛。空字符串与finance
行中的空字符串匹配。
你会想:
df3 = df1[(~df1.col1.isin(common.col1))|(~df1.col2.isin(common.col2))]
df3
Out[150]:
col1 col2
1 finance bh
3 accounting
4 IT
为了让行中df1
不df2
。
要获得专门
df3
col1 col2
3 accounting
4 IT
你可以尝试只选择那些具有非匹配的col1
。
df3 = df1[~df1.col1.isin(df2.col1)]
df3
Out[172]:
col1 col2
3 accounting
4 IT
要col1
& col2
独立检查匹配,并在任,同时具有NaN
我们比较不平等的/永远不会算作一个比赛,你可以使用
df3 = df1[(~df1.col1.isin(common.col1)|df1.col1.isnull())&(~df1.col2.isin(common.col2)|df1.col2.isnull())]
df3
Out[439]:
col1 col2
3 accounting NaN
4 IT NaN
假设你排除比赛在实际数据中使用实际的NaN
s,或者None
或np.nan
,而不是像本例中的空字符串。如果是后者,您需要添加
df1.replace('', np.nan, inplace=True)
df2.replace('', np.nan, inplace=True)
第一。
您是否尝试过'common = pd.merge(df1,df2,how ='left',on = ['col1','col2'])? – hallaksec
是的,它给了我相同的结果,我得到了common = df1.merge(df2,on = ['col1','col2']) – Enthusiast
你介意发布你的当前输出吗? – hallaksec