Malik
Malik

Reputation: 55

Creating a new column in a dataframe based on matches with another dataframe

I have two dataframes:

Dataframe 1:

ID  MONTH
1   2010-01
1   2010-03
1   2010-04
2   2010-01
3   2010-01
3   2010-02

Dataframe 2:

ID  MONTH
1   2010-01
3   2010-02

Is there a way to create a new column in Dataframe 1 based on row matches on both the ID and Month column in dataframe2?

So that the end result would look like:

  ID    MONTH Match
0  1  2010-01     Y
1  1  2010-03     N
2  1  2010-04     N
3  2  2010-01     N
4  3  2010-01     N
5  3  2010-02     Y

Upvotes: 1

Views: 90

Answers (1)

BENY
BENY

Reputation: 323226

Check with merge + indicator, return both will be Yes, left_only will be No

s=df1.merge(df2,indicator=True,how='left')
s['Match']=s.pop('_merge').map({'both':'Y','left_only':'N'})
s
Out[18]: 
   ID    MONTH Match
0   1  2010-01     Y
1   1  2010-03     N
2   1  2010-04     N
3   2  2010-01     N
4   3  2010-01     N
5   3  2010-02     Y

Upvotes: 3

Related Questions