Sean R
Sean R

Reputation: 337

In Pandas how can I test whether a value exists in two dataframes given a unique ID?

I have two dataframes like this where both frames can have multiple entries for each ID:

The first dataframe df1:

ID Amount
101 $30
102 $300
101 $35
103 $10
104 $220
103 $370
101 $500
105 $65

The second dataframe df2 has fewer rows but the same kind of information:

ID Amount
101 $35
102 $2
103 $25
104 $75
101 $30
102 $900

I want to compare the dataframes and find any rows that have the same Amount for a given ID in both frames. Here, for example, I want pandas to return ID 101 has having an entry for $30 in both frames. Right now my intuition is to append the dataframes like so:

df1 = df1.append(df2,ignore_index=True)
df1[df1.duplicated()]

But I wanted to know if there's a more 'pythonic' way to do this. Thanks!

Upvotes: 1

Views: 161

Answers (1)

Alexander Volkovsky
Alexander Volkovsky

Reputation: 2918

So you want something like inner join between dataframes. You can use pd.merge

pd.merge(df1, df2, on=["ID", "Amount"])

Upvotes: 2

Related Questions