简体   繁体   中英

Replace values in DF1 from DF2

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

DF1

在此处输入图像描述

DF2

在此处输入图像描述

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

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM