Skip to content
Advertisement

Vlookups in Pandas across 2 dataframe column

I have 2 dataframes and I wish to grab IDs matching with DF2 into df1 merged as separate columns. There are multiple columns to be added due to df2 having many different country names for a specific ID.

df1 looks like below:

JavaScript

df2 is like this:

JavaScript

What I am expecting df1 to look like:

JavaScript

I wish to bring if DF1 ID A is found in DF2 ID against a country then bring the country URL up next to df1 ID in a specific country column.

The way I am trying to achieve this is using a for loop with a map call below:

JavaScript

It runs for a certain amount of countries and then start throwing InvalidIndexError: Reindexing only valid with uniquely valued Index objects which I tried to overcome using a reset_index() function on both df1 and df2 but still after a certain amount of iterations, it throws me the same error.

Can someone suggest a more efficient way to do this or any way i could run it over all possible iterations?

Thanks,

Advertisement

Answer

Try as follows:

JavaScript

Explanation

JavaScript
  • Next, use df.merge to merge df and pivoted df2, joining the two on ID, and passing left to the how parameter to “use only keys from left frame”. (Leave how='left' out, if you are not interested in the row for ID with only NaN values.)

If you’re set on a particular column order, use e.g.:

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