Created
May 9, 2018 10:00
-
-
Save sainathadapa/eb3303975196d15c73bac5b92d8a210f to your computer and use it in GitHub Desktop.
anti-join-pandas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
def anti_join(x, y, on): | |
"""Return rows in x which are not present in y""" | |
ans = pd.merge(left=x, right=y, how='left', indicator=True, on=on) | |
ans = ans.loc[ans._merge == 'left_only', :].drop(columns='_merge') | |
return ans | |
def anti_join_all_cols(x, y): | |
"""Return rows in x which are not present in y""" | |
assert set(x.columns.values) == set(y.columns.values) | |
return anti_join(x, y, x.columns.tolist()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
After using this answer for a while (appreciate the original PO), I found out it runs into issues when there are duplicate ids in the DataFrame (if column
on
has non-unique values).So I developed some different functions that don't rely on
pd.DataFrame.merge()
but rather the more error-proof, super fast, and Pythonic set operations.Below are my functions, and anyone is welcome to use or read my StackOverflow post or GitHub repo for more details.
df_diff()
does "anti-join"df_overlap()
does "intersection"