pandas -通过在另一个数据框中查找来替换值 [英] Pandas - Replacing Values by Looking Up in an Another Dataframe

查看:42
本文介绍了 pandas -通过在另一个数据框中查找来替换值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Python3的pandas数据框中要解决一个问题.我有两个数据框-第一个是as;

I have a problem to solve in my pandas dataframe with Python3. I have two dataframes - the first one is as;

    ID Name  Linked Model 1  Linked Model 2  Linked Model 3
0  100    A          1111.0          1112.0             NaN
1  101    B          1112.0          1113.0          1115.0
2  102    C             NaN             NaN             NaN
3  103    D          1114.0             NaN             NaN
4  104    E          1114.0          1111.0          1112.0

第二个是

   Model ID Name
0      1111    A
1      1112  A,B
2      1113    C
3      1114    D
4      1115    Q
5      1116    Z
6      1117    E
7      1118    W

因此,代码应在-例如,在 Linked Model 1 列中查找值,并在第二个数据帧的 Name 列中找到相应的值,以便ID可以像结果中所示那样用名称替换;

So the code should look up the value in - for instance in Linked Model 1 column and find the corresponding value in Name column in the second dataframe so that the ID can be replaced with name just like as shown in the result;

因此,如您在结果输出中看到的,None保持为None(可以替换为numpy N/As),并且第二个数据框中的名称现在被替换为它们对应的 Model ID 第一个数据帧.

So as you can see in the result output, None stays as None (could be replaced numpy N/As) and the names from the second dataframe are now replaced with their corresponding Model IDs in the first dataframe.

我期待听到您的解决方案!

I am looking forward to hearing your solutions!

谢谢

推荐答案

初始化替换词典,然后使用

Initialise a replacement dictionary and use df.replace to map those IDs to Names.

m = df2.set_index('Model ID')['Name'].to_dict()
v = df.filter(like='Linked Model')
df[v.columns] = v.replace(m)

df
    ID Name Linked Model 1 Linked Model 2 Linked Model 3
0  100    A              A            A,B            NaN
1  101    B            A,B              C              Q
2  102    C            NaN            NaN            NaN
3  103    D              D            NaN            NaN
4  104    E              D              A            A,B

这篇关于 pandas -通过在另一个数据框中查找来替换值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆