python - 如何根据特定功能仅连接数据框中的非冗余行?
问题描述
我有一个非常棘手的问题,需要执行 1 和 2 的连接。输出应如下所示Out
。
1:
A B C | Y
1 1 5 1 <---- keep
2 2 5 1 <---- keep
2:
A B C | Y
1 1 6 0 <---- drop, because duplicated on subset=[A,B] with row of table 1.
1 2 6 0 <---- keep
3 3 6 0 <---- keep, despite duplicated on subset=[A,B] within this table.
3 3 7 0 <---- keep, despite duplicated on subset=[A,B] within this table.
Out:
A B C | Y
1 1 5 1
1 2 6 0
2 2 5 1
3 3 6 0
3 3 7 0
因此,正如您所看到的,我不能仅仅根据subset=[A,B]
连接后删除重复项。这也会删除行3 3 6 0
和3 3 7 0
.
总结一下:我只想连接 1 和 2。如果表 2 中有一行与表 1 中的 A 和 B 值相同,我只想保留表 1 的行。我不不想根据表 2 中的 A 和 B 删除其他重复项。
问候
解决方案
我有一个与 Sandipan 类似的解决方案,而是使用内部连接来完成。
import pandas as pd
df1 = pd.DataFrame([[1, 1, 5, 1], [2, 2, 5, 1]], columns = ['A','B','C', 'Y'])
df2 = pd.DataFrame([[1, 1, 6, 0], [1, 2, 6, 0], [3, 3, 6, 0], [3, 3, 7, 0]], columns = ['A','B','C', 'Y'])
# Add an index for df2
df2['idx'] = range(len(df2))
# Find the index of common rows by inner join
common_row = pd.merge(df1, df2, on=['A','B'], how='inner').idx.tolist()
# Remove common rows in df2
df2 = df2[~df2.idx.isin(common_row)]
df2 = df2.iloc[:,0:-1]
# Concat df1 and df2
df = pd.concat([df1, df2])
df = df.sort_values(by=['A','B'], ascending=[True, True])
df
推荐阅读
- r - 不确定如何将两组数据与两个数据集中的通用名称组合起来
- firebase - 缺少firebase api?我该如何解决?
- angular - Ionic 4 SQLite“无法读取未定义的属性'then'”错误
- javascript - 如果输入文件在没有表单的ajax请求中作为数组元素传递,为什么数组对象变为空
- nginx - 服务器上支持的 nginx 基本身份验证
- delphi - 关于使用 TIdTcpServer 的 FDQuery
- bash - 来自 Git Bash Here 的 Jupyter Notebook
- javascript - 来自 webpack 文档站点的代码问题
- forms - 我需要帮助将电子邮件注册表单的所有元素放在同一行
- python - Python - 使用 side_effect 模拟在类的 init 内部调用的函数