Demi
Demi

Reputation: 234

How to assign variable to a column based on a condition from another column?

I have 2 datasets, which look like this:

  1. Dataset 1
Link Domain
https//:example/page/uk example
https//:another.good-example.com good-example
  1. Dataset 2
ID Domain Ad Source
1 smth NaN
2 example NaN
3 good-example NaN
4 another-smth NaN

What i need is if Domain in Dataset 2 is in Dataset 1, then Ad Source should be 'Adwords' So, the end result is:

ID Domain Ad Source
1 smth NaN
2 example Adwords
3 good-example Adwords
4 another-smth NaN

I have tried this, but it didn't work:

for links in Dataset1['Domain']:
    if links in Dataset2['Domain']:
        return Dataset2['Ad Source']='Adwords'

Upvotes: 0

Views: 29

Answers (1)

Corralien
Corralien

Reputation: 120479

Use indexing and isin to check domains:

Dataset2.loc[Dataset2['Domain'].isin(Dataset1['Domain']), 'Ad Source'] = 'Adwords'
print(Dataset2)

# Output
   ID        Domain Ad Source
0   1          smth       NaN
1   2       example   Adwords
2   3  good-example   Adwords
3   4  another-smth       NaN

Upvotes: 1

Related Questions