2

I want to compare two pandas-tables by two columns. Consider following example: I would like to get a boolean Series which indicates True ONLY if BOTH conditions match. I tried is.in() without much success. I could either loop over "One" or combine (add) both columns together in both dataframes, but is there some built-in functionality of pandas that would allow for such (nested) comparisons involving two pairs of columns?

tab1 = pd.DataFrame({"One": [1, 1, 2, 3],
                     "Two": ["A", "B", "C", "C"]})

tab2 = pd.DataFrame({"One": [1, 2, 2, 3, 3],
                     "Two": ["A", "A", "B",  "A","C"]})

# Desired Result (New column in tab1): [True, False, False, True]

EDIT: The second table is more like a lookup table. They do not have the same shape. Should have made that clearer.

2 Answers 2

2
tab1.eq(tab2).all(1)
0     True
1    False
2    False
3     True
dtype: bool

Update

tab1.merge(tab2,indicator=True,how='left')['_merge'].eq('both')
0     True
1    False
2    False
3     True
Name: _merge, dtype: bool
Sign up to request clarification or add additional context in comments.

2 Comments

I was not very clear in my example. The second dataframe is acutally a lookup df with a different shape.
Yes, this looks exactly like what I wanted. Coming from R, the pandas world is still a bit exotic for me. Thank you!
1

When you do columnar comparison in Pandas, you get a column/vector of boolean values. You can do element-wise boolean operations between these results using Python's bit-wise operations (so, & instead of and and | instead of or). You just need to be careful about order of operations, since bitwise comparisons have higher precedence than comparisons. So,

(tab1.One == tab2.One) & (tab1.Two == tab2.Two)

2 Comments

I did not describe the problem correctly. The 2 dataframes do not have the same shape.
Well that's really important. You'll need some way to align the rows, then, either using a key of some sort in another column or some other lookup/logic. You don't have a unique "primary key" column in the tables you show, so you'll need to define how the rows should align or else this is an undefined problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.