相关疑难解决方法(0)

Pandas:通过多列查找另一个DataFrame中不存在的行

和这个python pandas一样:如何在一个数据帧中找到行但在另一个数据帧中找不到? 但有多列

这是设置:

import pandas as pd

df = pd.DataFrame(dict(
    col1=[0,1,1,2],
    col2=['a','b','c','b'],
    extra_col=['this','is','just','something']
))

other = pd.DataFrame(dict(
    col1=[1,2],
    col2=['b','c']
))
Run Code Online (Sandbox Code Playgroud)

现在,我想选择其他行中df不存在的行.我想用col1和做选择col2

在SQL中我会这样做:

select * from df 
where not exists (
    select * from other o 
    where df.col1 = o.col1 and 
    df.col2 = o.col2
)
Run Code Online (Sandbox Code Playgroud)

在熊猫我可以做这样的事情,但感觉非常难看.如果df具有id-column,则可以避免部分丑陋,但并不总是可用.

key_col = ['col1','col2']
df_with_idx = df.reset_index()
common = pd.merge(df_with_idx,other,on=key_col)['index']
mask = df_with_idx['index'].isin(common)

desired_result =  df_with_idx[~mask].drop('index',axis=1)
Run Code Online (Sandbox Code Playgroud)

那么也许有一些更优雅的方式?

python join pandas

22
推荐指数
2
解决办法
2万
查看次数

标签 统计

join ×1

pandas ×1

python ×1