首页 > 解决方案 > 比较两个数据帧,如果数据不同则更新数据帧

问题描述

我有两个数据框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

如何实现?

标签: pythonpandasdataframe

解决方案


如果我理解正确的逻辑。. .

# 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

推荐阅读