python - 比较两个数据帧,如果数据不同则更新数据帧
问题描述
我有两个数据框df1,df2,df2包含更新信息,df1是从数据库中获取的旧数据。因此,我们正在尝试创建新的数据帧 df3、df4。df3(应该包含新记录(ids)),df4(应该包含修改过的记录)
例子:
df1 =
id 姓名得分
111 Jack 2.17
112 Nick 1.11
113 Zoe 4.12
df2 =
id 姓名 分数
111 Jack 2.17
112 Sick 1.10
113 Zoe 4.12
114 Jay 12.3
所以,我需要一个新的数据框 df3 (new id) 说,
df3 =
id姓名评分
114周杰伦12.3
我需要一个新的数据框 df4(相同的 id 不同的数据)说,
df4 =
id 姓名 评分
112 生病 1.10
如何实现?
解决方案
如果我理解正确的逻辑。. .
# imports
import pandas as pd
from io import StringIO
# sample data
s1 = """id Name score
111 Jack 2.17
112 Nick 1.11
113 Zoe 4.12"""
s2 = """id Name score
111 Jack 2.17
112 Sick 1.10
113 Zoe 4.12
114 Jay 12.3"""
df1 = pd.read_csv(StringIO(s1), sep=' ')
df2 = pd.read_csv(StringIO(s2), sep=' ')
# use boolean indexing with isin
# new id in df2 that is not in df1
df3 = df2[~df2['id'].isin(df1['id'])]
# where id is the same but name or score is different
# also does not include the data where id is in the newly created df3
df4 = df2[~(df2[['Name', 'score']].isin(df1[['Name', 'score']]).any(1) | df2['id'].isin(df3['id']))]
df3
id Name score
3 114 Jay 12.3
df4
id Name score
1 112 Sick 1.1
推荐阅读
- pip - Can't configure spatialite because it can't detect PROJ (libproj)
- wordpress - 令牌在WordPress中一次又一次地过期或撤销
- android - 使用 LightCompressor 的视频压缩不起作用
- python - Mac 不读取 pytube 包
- python - 如何从雅虎财经获取日期
- mongodb - 使用 JSON 视图插入带有日期时间字段的文档
- mysql - 我无法使用 docker-compose 从服务器容器连接 mysql 容器
- matlab - inf 区间中的 MATLAB 卷积
- compiler-construction - 移位归约和归约归约与 LR 冲突
- flutter - 如何防止修改后的应用程序在颤振中运行?