Reputation: 5
Hi I want to compare two columns in a pandas dataframe to see if a value is in any row of a column.
Table: 1
| Animals_1 | Count |
|-----------|--------|
| Dog | 1 |
| Cat | 2 |
| Squirrel | 3 |
Table:2
| Animals_2 | Count |
|-----------|--------|
| Giraffe | 2 |
| Dog | 1 |
| Cat | 1 |
So I want to check to see if Dog from table 1 is in any rows in column 1 of table 2. I am new to python and using pandas to read table dataframe.
Upvotes: 0
Views: 255
Reputation: 9619
import pandas as pd
df1 = pd.DataFrame({"Animals_1":["Dog","Cat","Squirrel"],"Count":[1,2,3]})
df2 = pd.DataFrame({"Animals_2":["Giraffe","Dog","Cat"],"Count":[2,1,1]})
df1['compare'] = df1['Animals_1'].isin(df2['Animals_2'])
Output df1
:
Animals_1 | Count | compare | |
---|---|---|---|
0 | Dog | 1 | True |
1 | Cat | 2 | True |
2 | Squirrel | 3 | False |
Upvotes: 1