Home > database >  Replace values in DF1 from DF2
Replace values in DF1 from DF2

Time:04-05

enter code here Please if you can help me with this, I have two dataframes.

DF1

enter image description here

DF2

enter image description here

These are the two datasets i have,

So i want to first check the column name is available in DF1. If yes then whatever the code is replace it with the city name.

I want the process to be iterative so i don't have to add each column name to find the corresponding value.

I have tried couple of ways but all those had one database with unique index but my DF1 don't have a unique index.

Please if you can help. Thank you

CodePudding user response:

Edit : the city ID is not unique in DF1

You can define a dict by country with the keys being the city ID and the value being the city name

You can then use a apply column by column to do the trick.

def get_city_name_from_id(id,city_dict):
    if id in city_dict.keys():
        return city_dict[id]

for e in list(DF2.columns)[1::]: # Skip the first column of DF2
    partial_DF1=DF1[DF1['country']==e]
    partial_city_dict=dict(zip(partial_DF1.Code, partial_DF1.city))
    DF2[e]=DF2[e].apply(lambda x:get_city_name_from_id(x,partial_city_dict))
  • Related