Python, Pandas: 比较dataframes,分别保留旧的、更新的和新的

Python, Pandas: Compare dataframes and keep old, updated and new ones separately

晚上好,

假设我有两个数据帧:

数据帧 1:

id    |    first_name    |    last_name    |    age    |    personnel_number
1     |    Jane          |    Doe          |    37     |    0045ac
2     |    John          |    Doe          |    35     |    0102ha
3     |    Sarah         |    Smith        |    28     |    1003px
17    |    Michael       |    Mueller      |    61     |    0800pw

数据框 2:

id    |    first_name    |    last_name    |    age    |    personnel_number
1     |    Jane          |    Doe          |    37     |    0045ac
2     |    John          |    Doe          |    35     |    0102ha
3     |    Sarah         |    Smith        |    41     |    1003px
4     |    Sam           |    Smith        |    24     |    0017ix

我知道,使用以下代码我得到了一个新的数据框,其中更新了现有行并添加了新行...

df_comp = df2.set_index('personnel_number').combine_first(df1.set_index('personnel_number')).reset_index()

...实现此目的:

组合数据框:

id    |    first_name    |    last_name    |    age    |    personnel_number
1     |    Jane          |    Doe          |    37     |    0045ac
2     |    John          |    Doe          |    35     |    0102ha
3     |    Sarah         |    Smith        |    41     |    1003px
17    |    Michael       |    Mueller      |    61     |    0800pw
4     |    Sam           |    Smith        |    24     |    0017ix

我的问题:有没有办法用以下数据实现三个而不是一个组合数据帧:

备注

感谢您的帮助和建议,祝周末愉快!

您可以尝试使用 indicator 进行外部合并,然后将一些条件跟在 groupby 之后,然后存储在字典中:

out = df2.merge(df1,how='outer',indicator='group')

c = out.groupby("personnel_number",sort=False).transform('nunique').gt(1).any(1)

out['group'] = (np.select([out['group'].eq("both"),out['group'].ne("both") & c,
                           out['group'].isin(['both','left_only']) & ~c],
                          ['Already_exists','Updated','New']))

d = dict(iter(out.groupby("group")))

输出: