python - 外部合并 2 个数据框 - 左右外部不同
问题描述
我有 2 个DataFrames
展示产品。一个被称为current
另一个future
。
current
表示数据库中的当前状态
future
表示数据库的新状态
假设他们只有 2 列:“id”和“name”。我需要合并它们并附加一个具有四个值的列:new
、none
和.update
delete
new
- 该产品不在current
数据框中
none
- 这个产品在两个数据框中,没有值改变
update
- 这个产品在两个数据框中,但它至少有一个不同的值
delete
- 该产品在current
但不在delete
数据框中
我想使用outer
join,因为产品很多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
...
解决方案
您可以使用 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
推荐阅读
- python - 如何从 QCalendarWidget 对象获取日期并将其设置为最小日期?
- sql - 使用 case 语句检查 SQL 表中是否存在记录
- c# - InvalidDataException:超过多部分正文长度限制 16384
- python - API 网关主体映射移动?
- jestjs - toEqual 的变体,它使用类属性的方式与使用类方法的方式相同
- php - 当别名域是请求的资源时捕获请求的 URL
- go - 使用事务运行 Go 测试
- c++ - 在运行时访问 C++17 中元组的随机子集
- terraform - 如何让 ECS 服务进行强制重新部署?
- java - 如何使用 Java 在 YouTube Data API v3 中设置 nextPageToken?