pandas - Pandas 用另一个数据框更新一个数据框
问题描述
我有2个数据框:
df1:
col1 col2 col3
A B C
df2:
col1 col2 col3 col4
A B C D
我想用 df2 更新 df1,这样如果我匹配 col1、col2、col3,然后用 col4 替换 col3
df_want:
col1 col2 col3
A B D
在 SQL 中,它将是:
select df1.col1,df1.col2,coalesce( df2.col4,df1.col3) as col3
from df1 left join df2 on df1.col1=df2.col1 and df1.col2=df2.col2 and df1.col3=df2.col3
解决方案
Using merge
df1=df1.merge(df2,how='left')
df1.col3=df1.col4.fillna(df1.col3)
df1
Out[189]:
col1 col2 col3 col4
0 A B D D
df1.drop('col4',1,inplace=True)
df1
Out[191]:
col1 col2 col3
0 A B D
推荐阅读
- c# - 如何在哈希表中添加范围?
- gcc - 用于 MAJIQ 管道安装的 Clang 编译器和 gcc 问题
- nginx - ngx_http_script_compile 与 ngx_http_compile_complex_value
- php - 在 PHP 中使用存储在数据库中的 MySQL 查询
- c# - 如何在 .NetCore 项目中为本地开发设置 Papercut SMTP 服务器
- javascript - 组合两个点击函数的方法,当一个点击函数有一个窗口大小的if语句时
- applescript - Applescript 等到模态消失
- sql - 根据 SQL Server 中的条件返回前 1 条记录
- html - 当某些行有表情符号而某些行没有时,如何使表格中的行垂直对齐?
- excel - 通过 VBA 将 Crystal Report 导出为 pdf