首页 > 解决方案 > 外部合并 2 个数据框 - 左右外部不同

问题描述

我有 2 个DataFrames展示产品。一个被称为current另一个future

current表示数据库中的当前状态 future表示数据库的新状态

假设他们只有 2 列:“id”和“name”。我需要合并它们并附加一个具有四个值的列:newnone和.updatedelete

new- 该产品不在current数据框中

none- 这个产品在两个数据框中,没有值改变

update- 这个产品在两个数据框中,但它至少有一个不同的值

delete- 该产品在current但不在delete数据框中

我想使用outerjoin,因为产品很多pandas,合并效率很高。

例子:

current = DataFrame(data=[
    [1,'a'],
    [2,'name'],
    [3,'c'],
],columns=['id','name'])

future = DataFrame(data=[
    [1,'a'],
    [2,'other_name'],
    [4,'c'],
],columns=['id','name'])

# DESIRED result after merging

 [1,'a','none']
 [2,'other_name','update']
 [3,'c','delete']
 [4,'c','new']

我试过这个:

DataFrame.merge(current,future,how='outer',on='id')
   id name_x      name_y
0   1      a           a
1   2   name  other_name
2   3      c         NaN
3   4    NaN           c

你能帮我搬家吗?在现实世界中,有很多列,我不能只检查name_x是否None...

标签: pythonpandas

解决方案


您可以使用 numpy select 来传递条件,

df = current.merge(future, 'outer', on = 'id')
condlist = [(df['name_x'] == df['name_y']), ((df['name_x'] != df['name_y'])&(df[['name_x','name_y']].notnull().all(1))), (df['name_x'].isnull()), (df['name_y'].isnull())]
choicelist = ['None', 'update', 'new', 'delete']
df['new'] = np.select(condlist, choicelist)


    id  name_x  name_y      new
0   1   a       a           None
1   2   name    other_name  update
2   3   c       NaN         delete
3   4   NaN     c           new

推荐阅读