[英]Replace values in DF1 from DF2
enter code here Please if you can help me with this, I have two dataframes.请在此处输入代码如果你能帮我解决这个问题,我有两个数据框。
DF1 DF1
DF2 DF2
These are the two datasets i have,这是我拥有的两个数据集,
So i want to first check the column name is available in DF1.所以我想首先检查列名在 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.我尝试了几种方法,但所有这些方法都有一个具有唯一索引的数据库,但我的 DF1 没有唯一索引。
Please if you can help.如果你能帮忙,请。 Thank you
谢谢
Edit: the city ID is not unique in DF1编辑:城市 ID 在 DF1 中不是唯一的
You can define a dict by country with the keys being the city ID and the value being the city name您可以按国家/地区定义字典,键是城市 ID,值是城市名称
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.