使用另一个具有相应替换的 Pandas df 替换 Pandas 列中的值 [英] Replace values in a pandas column using another pandas df which has the corresponding replacements

查看:110
本文介绍了使用另一个具有相应替换的 Pandas df 替换 Pandas 列中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 inventory 的 pandas df,它有一列包含 Part Numbers (AlphaNumeric).其中一些零件号已被取代,我有另一个名为 replace_with 的 df,其中包含两列,'old part numbers''new part numbers'.例如:

I have a pandas df named inventory, which has a column containing Part Numbers (AlphaNumeric). Some of those part numbers have been superseded and I have another df named replace_with containing two columns, 'old part numbers' and 'new part numbers'. For example:

库存具有以下值:

* 123AAA
* 123BBB
* 123CCC
......

和 replace-with 具有像

and replace-with has values like

**oldPartnumbers**   .....        **newPartnumbers**  

* 123AAA        ............            123ABC
* 123CCC          ...........          123DEF

所以,我需要用新数字替换库存中的相应值.更换后的库存将如下所示:

SO, i need to replace corresponding values in inventory with the new numbers. After replacement inventory will look like as follows:

* 123ABC
* 123BBB
* 123DEF

在python中有没有一种简单的方法可以做到这一点?谢谢!

Is there a simple way to do that in python? Thanks!

推荐答案

假设您有 2 个 df,如下所示:

Let say you have 2 df as follows:

import pandas as pd
df1 = pd.DataFrame([[1,3],[5,4],[6,7]], columns = ['PN','name'])
df2 = pd.DataFrame([[2,22],[3,33],[4,44],[5,55]], columns = ['oldname','newname'])

df1:

    PN  oldname
0   1   3
1   5   4
2   6   7

df2:

    oldname  newname
0   2        22
1   3        33
2   4        44
3   5        55

在它们之间运行左连接:

run left join between them:

temp = df1.merge(df2,'left',left_on='name',right_on='oldname')

温度:

    PN      name     oldname    newname
0   1        3         3.0      33.0
1   5        4         4.0      44.0
2   6        7         NaN      NaN

然后计算新的name列并替换它:

then calculate the new name column and replace it:

df1['name'] = temp.apply(lambda row: row['newname'] if pd.notnull(row['newname']) else row['name'], axis=1)

df1:

    PN  name
0   1   33.0
1   5   44.0
2   6   7.0

或者,作为一个班轮:

df1['name'] = df1.merge(df2,'left',left_on='name',right_on='oldname').apply(lambda row: row['newname'] if pd.notnull(row['newname']) else row['name'], axis=1)

这篇关于使用另一个具有相应替换的 Pandas df 替换 Pandas 列中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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