首页 > 解决方案 > 如何根据特定功能仅连接数据框中的非冗余行?

问题描述

我有一个非常棘手的问题,需要执行 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 03 3 7 0.

总结一下:我只想连接 1 和 2。如果表 2 中有一行与表 1 中的 A 和 B 值相同,我只想保留表 1 的行。我不不想根据表 2 中的 A 和 B 删除其他重复项。

问候

标签: pythonpandasnumpydataframeouter-join

解决方案


我有一个与 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

推荐阅读