消除部分匹配的熊猫数据帧行

E.K*_*.K. 5 python merge pandas

我想通过比较 A 列和 B 列中的值来比较两个 Pandas 数据帧并找出仅在 df1 中的行。我觉得我可以通过使用合并以某种方式执行此操作,但无法弄清楚..

import pandas as pd

df1 = pd.DataFrame([[1,11, 111], [2,22, 222], [3, 33, 333]], columns=['A', 'B', 'C'])
df2 = pd.DataFrame([[1, 11]], columns=['A', 'B'])
Run Code Online (Sandbox Code Playgroud)

df1

    A   B   C
0   1   11  111
1   2   22  222
2   3   33  333
Run Code Online (Sandbox Code Playgroud)

df2

    A   B
0   1   11
Run Code Online (Sandbox Code Playgroud)

我想看的数据框

    A   B   C
1   2   22  222
2   3   33  333
Run Code Online (Sandbox Code Playgroud)

vmg*_*vmg 1

基于这种方法

import pandas as pd

df1 = pd.DataFrame([[1,11, 111], [2,22, 222], [3, 33, 333]], columns=['A', 'B', 'C'])
df2 = pd.DataFrame([[1, 11]], columns=['A', 'B'])
Run Code Online (Sandbox Code Playgroud)

连接数据帧:

df = pd.concat([df1, df2])
df.reset_index(drop=True)
Run Code Online (Sandbox Code Playgroud)

根据您想要的比较列进行分组 - 在您的情况下,A并且B

df_gpby = df.groupby(['A','B'])
Run Code Online (Sandbox Code Playgroud)

获取只有一个值的组的索引 - 即 unique A,B对:

idx = [x[0] for x in df_gpby.groups.values() if len(x) == 1]
Run Code Online (Sandbox Code Playgroud)

按索引对串联数据帧进行子集化:

df.iloc[idx]
Run Code Online (Sandbox Code Playgroud)

结果是:

    A   B   C
1   2   22  222
2   3   33  333
Run Code Online (Sandbox Code Playgroud)