简体   繁体   English

从 DF2 替换 DF1 中的值

[英]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.

相关问题 Python Pandas查找并替换df2中的df1值 - Python Pandas lookup and replace df1 value from df2 pandas 如何从 df2 获取 df1 的值,而 df1 和 df2 的值在列上重叠 - pandas how to get values from df2 for df1 while df1 and df2 have values overlapped on column(s) 如果值在 df1 的范围内,Pandas 会将标签从 df1 应用到 df2 - Pandas apply labels from df1 to df2 if values are within a range in df1 使用来自 df1 的最大值和来自 df2 的相应值(相同位置)创建新的 df3 - create new df3 with max values from df1 and corresponding values (same position) from df2 根据 df1 上的条件创建 pd 系列,并报告来自 df2 或 df3 的值 - Create pd series based on conditions on df1, and reporting values from df2 or df3 用 df2 中的值替换 df1 中的值,如果值被替换,则在新的 col 中分配代码 - Replace values in df1 with values in df2 and then assign code in new col if value was replaced 如何向 dataframe (df1) 添加一个新列,这是另一个 dataframe (df2) 中 df1 的多个查找值的总和 - How can I add a new column to a dataframe (df1) that is the sum of multiple lookup values from df1 in another dataframe (df2) 将df1与df2匹配,然后将其替换为索引值(非内部联接) - Match df1 with df2 and Replace it with index value (Not Inner Join) 如何通过匹配 df1 中与 df2 索引和列名匹配的列值来用 df1 中的数据填充 df2 - How to fill df2 with data from df1 by matching column values from df1 which match df2 index and column names 合并 df1 中的值对应于 df2 中的值的行 - Combining rows where values in df1 correspond to values in df2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM