Rahul rajan
Rahul rajan

Reputation: 1266

Inner join and update a column in Pandas

I have two dataframes. I need update one dataframe based on the conditions from the other dataframe.

Dataframe 1

Tracking_Nbr    Flag
770310517324    Y
787757679168    Y
770320639804    Y
787819140020    Y
787806525476    Y
787817272220    N
787787101424    N

Dataframe 2

Tracking_Nbr Class  Flag
770310517324    B   Y
787757679168    B   Y
770320639804    B   Y
787819140020    B   Y
787806525476    B   Y
787817272220    R   N
787787101424    R   N

Update Conditions

a.  If Flag == ‘Y’ and Class == ‘B’, change your data  Flag to ‘N’ in dataframe A
b.  If Flag == ‘N’ and Class == ‘R’, change your data  Flag to ‘Y’ in dataframe A

How this can be done?

Upvotes: 1

Views: 1251

Answers (1)

BENY
BENY

Reputation: 323366

You can try this.

df2['Updated']=np.where((df2.Class=='B')&(df2.Flag=='Y'),'N',np.where((df2.Class=='R')&(df2.Flag=='N'),'Y',df2.Flag))
df1.Flag=df1['Tracking_Nbr'].map(df2.set_index('Tracking_Nbr').Updated)
df1
Out[594]: 
   Tracking_Nbr Flag
0  770310517324    N
1  787757679168    N
2  770320639804    N
3  787819140020    N
4  787806525476    N
5  787817272220    Y
6  787787101424    Y

Upvotes: 1

Related Questions