Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 合并数据帧,添加/更新字段_Python_Python 3.x_Pandas_Merge - Fatal编程技术网

Python 合并数据帧,添加/更新字段

Python 合并数据帧,添加/更新字段,python,python-3.x,pandas,merge,Python,Python 3.x,Pandas,Merge,我正试图在person\u id上合并/连接两个带有熊猫的数据帧。 如果找到匹配项,则其应添加或更新电子邮件字段。 它不应该创建新行,因为dosnt存在于表A中 表A +-----------+-----------------+------+ | person_id | email | lang | +-----------+-----------------+------+ | 1 | | EN | |

我正试图在person\u id上合并/连接两个带有熊猫的数据帧。 如果找到匹配项,则其应添加或更新电子邮件字段。 它不应该创建新行,因为dosnt存在于表A中

表A

+-----------+-----------------+------+
| person_id |      email      | lang |
+-----------+-----------------+------+
|         1 |                 | EN   |
|         2 | tes2@foo.com    | FR   |
|         3 | tes3@barbar.com | DK   |
+-----------+-----------------+------+
表B

+-----------+--------------+------+
| person_id |    email     | kids |
+-----------+--------------+------+
|         1 | tes1@foo.com |    2 |
|         2 | tes2@foo.com |    0 |
|         3 | tes3@foo.com |    0 |
|         4 | tes4@foo.com |    1 |
+-----------+--------------+------+
我想要的结果是

+-----------+--------------+------+------+
| person_id |    email     | kids | lang |
+-----------+--------------+------+------+
|         1 | tes1@foo.com |    2 | EN   |
|         2 | tes2@foo.com |    0 | FR   |
|         3 | tes3@foo.com |    0 | DK   |
|         4 | tes5@foo.com |    1 |      |
+-----------+--------------+------+------+
我试过了

df_merged=pd.merge(Table_A,Table_B,on=["person_id"], how="left")

这为我提供了正确的字段,但也创建了email_x和email_y字段。我只需要一个电子邮件字段。

这里有一个临时解决方案

合并数据帧并添加后缀

dfNew = df.merge(df1, left_index=True, right_index=True,how='outer', suffixes=('_y', ''))

     #result
     person_id_y       email_y  lang  person_id         email   kids
            1             None   EN         1    tes1@foo.com     2
            2     tes2@foo.bar   FR         2    tes2@foo.com     0
            3  tes2@barbar.com   DK         3    tes3@foo.com     0
          NaN              NaN  NaN         4    tes4@foo.com     1
然后只需筛选所需的列

dfNew = dfNew[['person_id','email','kids','lang']]

person_id         email  kids lang
        1  tes1@foo.com     2   EN
        2  tes2@foo.com     0   FR
        3  tes3@foo.com     0   DK
        4  tes4@foo.com     1  NaN

我认为你必须使用
.join