복붙노트

[PYTHON] Pandas : 여러 DataFrame에 존재하지 않는 행을 여러 열로 찾습니다.

PYTHON

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']
))

이제는 df에서 다른 행에 존재하지 않는 행을 선택하려고합니다. 나는 col1과 col2에 의해 선택을하고 싶다.

SQL에서는 다음과 같은 작업을 수행했습니다.

select * from df 
where not exists (
    select * from other o 
    where df.col1 = o.col1 and 
    df.col2 = o.col2
)

그리고 판다 스에서 이런 식으로 할 수는 있지만 아주 추해 보입니다. 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)

그래서 좀 더 우아한 방법이 있을까요?

해결법

  1. ==============================

    1.0.17.0부터 병합을 위해 전달할 수있는 새로운 표시기 매개 변수가 있습니다.이 매개 변수는 행이 왼쪽, 오른쪽 또는 둘 다에만 존재하는지 여부를 알려줍니다.

    0.17.0부터 병합을 위해 전달할 수있는 새로운 표시기 매개 변수가 있습니다.이 매개 변수는 행이 왼쪽, 오른쪽 또는 둘 다에만 존재하는지 여부를 알려줍니다.

    In [5]:
    merged = df.merge(other, how='left', indicator=True)
    merged
    
    Out[5]:
       col1 col2  extra_col     _merge
    0     0    a       this  left_only
    1     1    b         is       both
    2     1    c       just  left_only
    3     2    b  something  left_only
    
    In [6]:    
    merged[merged['_merge']=='left_only']
    
    Out[6]:
       col1 col2  extra_col     _merge
    0     0    a       this  left_only
    2     1    c       just  left_only
    3     2    b  something  left_only
    

    이제 'left_only'행만 선택하여 병합 된 df를 필터링 할 수 있습니다.

  2. ==============================

    2.재미있는

    재미있는

    cols = ['col1','col2']
    #get copies where the indeces are the columns of interest
    df2 = df.set_index(cols)
    other2 = other.set_index(cols)
    #Look for index overlap, ~
    df[~df2.index.isin(other2.index)]
    

    보고:

        col1 col2  extra_col
    0     0    a       this
    2     1    c       just
    3     2    b  something
    

    좀 더 우아 해 보입니다 ...

  3. from https://stackoverflow.com/questions/32652718/pandas-find-rows-which-dont-exist-in-another-dataframe-by-multiple-columns by cc-by-sa and MIT license