简体   繁体   中英

Comparing two columns using pandas

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM