Skip to content
Advertisement

Merge inside the merge only if the first doesn’t return a match

I have 3 dataframes (df1, df2 & df3), the main one (df1) and two additional ones which contain 1 column amongst others that I want to bring over to the main dataframe.

Sample dfs:

JavaScript

df1 enter image description here df2 enter image description here

and df3 enter image description here

I am using the following code:

JavaScript

enter image description here

Then for the two empty strings for the “Objective” column I want to continue with a second merge (or an excel vlookup which I guess are the same), to fill in those empty ones.

Code that I thought would be used for the second merge:

JavaScript

Desired final output.

JavaScript

enter image description here

Any suggestions would be more than appreciated!

Advertisement

Answer

After merging the three dataframes, you can use mask or np.where to conditionally assign value

JavaScript
JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement