How to efficiently find the inverse intersection between two large dataframes with pandas?

ICu*_*tis 5 python intersection bigdata dataframe pandas

I am trying to find the inverse intersection between two large dataframes. I got it to work with the code snipped hereafter. Unfortunately, this approach is "too slow" on large dataframes as is further described below. Can you think of a quicker way to compute this outcome?

import pandas as pd

df_1 = pd.DataFrame({'a': [8, 2, 2],
                     'b': [0, 1, 3],
                     'c': [0, 2, 2],
                     'd': [0, 2, 2],
                     'e': [0, 2, 2]})

df_2 = pd.DataFrame({'a': [8, 2, 2, 2, 8, 2],
                     'b': [0, 1, 1, 6, 0, 1],
                     'c': [0, 3, 2, 2, 0, 2],
                     'd': [0, 4, 2, 2, 0, 4],
                     'e': [0, 1, 2, 2, 0, 2]})

l_columns = ['a','b','e']

def df_drop_df(df_1, df_2, l_columns):
    """
    Eliminates all equal rows present in dataframe 1 (df_1) from dataframe 2 (df_2) depending on a subset of columns (l_columns)

    :param df_1: dataframe that defines which rows to be removed
    :param df_2: dataframe that is reduced
    :param l_columns: list of column names, present in df_1 and df_2, that is used for the comparison

    :return df_out: final dataframe
    """
    df_1r = df_1[l_columns]
    df_2r = df_2[l_columns].reset_index()

    df_m = pd.merge(df_1r, df_2r, on=l_columns, how='inner')
    row_indexes_m = df_m['index'].to_list()

    row_indexes_df_2 = df_2.index.to_list()
    row_indexes_out = [x for x in row_indexes_df_2 if x not in row_indexes_m]

    df_out = df_2.loc[row_indexes_out]
    return df_out
Run Code Online (Sandbox Code Playgroud)

Giving the following correct result:

#row_indexes_out = [1,3]

df_output = df_drop_df(df_1, df_2, l_columns)
df_output

({'a': [2, 2],
  'b': [1, 6],
  'c': [3, 2],
  'd': [4, 2],
  'e': [1, 2]})
Run Code Online (Sandbox Code Playgroud)

However, for the actual application, the size of the dataframes has the following dimensions, which takes roughly 30min to compute on my local machine:

variable shape
df1 (3300,77)
df2 (642000,77)
l_columns list 12
df_out (611000,77)

(This means that each row present in df_1 is roughly 10 times in df_2)

Can you think of a quicker way to compute this outcome?

jot*_*wie 4

您可以尝试替换以下行:

row_indexes_df_2 = df_2.index.to_list()
row_indexes_out = [x for x in row_indexes_df_2 if x not in row_indexes_m]

df_out = df_2.loc[row_indexes_out]
Run Code Online (Sandbox Code Playgroud)

通过波形符运算符:

df_out = df_2.loc[~df_2.index.isin(row_indexes_m)]
Run Code Online (Sandbox Code Playgroud)

它应该大大减少时间。