简体   繁体   English

比较 pandas 中 2 个不同数据帧中的列(两个数据帧中只有 1 列相同)

[英]Compare a column in 2 different dataframes in pandas (only 1 column is same in both dataframes)

I have 2 dataframes df1 and df2 and I want to compare 'col1' of both dataframes and get the rows from df1 where 'col1' values don't match.我有 2 个数据帧df1df2 ,我想比较两个数据帧'col1'并从df1中获取'col1'值不匹配的行。 Only 'col1' is common in both dataframes.只有'col1'在两个数据帧中很常见。

Suppose I have:假设我有:

df1 = pd.DataFrame({
    'col1': range(1, 6),
    'col2': range(10, 60, 10),
    'col3': [*'abcde']
})
df2 = pd.DataFrame({
    'col1': range(1, 4),
    'cola': ['Aa', 'bcd', 'h'],
    'colb': [12, 'sadf', 'dd']
})

print(df1)

   col1  col2 col3
0     1    10    a
1     2    20    b
2     3    30    c
3     4    40    d
4     5    50    e

print(df2)

   col1 cola  colb
0     1   Aa    12
1     2  bcd  sadf
2     3    h    dd

I want to get:我想得到:

   col1  col2 col3
0     4    40    d
1     5    50    e

Quick and Dirty又快又脏

df1.append(df1.merge(df2.col1)).drop_duplicates(keep=False)

   col1  col2 col3
3     4    40    d
4     5    50    e

Just use this:-只需使用这个: -

df1[~df1['col1'].isin(df2['col1'])]

Now if you print above code you will get your desired output:-现在,如果您打印上面的代码,您将获得所需的 output:-

   col1  col2 col3
3     4    40    d
4     5    50    e

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何连接两个具有相同列的 Pandas 数据帧,但前提是两个数据帧中的一列的值相同? - How to concat two Pandas dataframes that have the same columns but only if the value of one column in both dataframes is the same? 如何按列比较不同的数据框? - How to compare different dataframes by column? 比较两个不同大小的数据帧并在 Pandas 中创建一个新列 - Compare two dataframes with different size and create a new column in Pandas 基于列比较数据帧并仅保留两个数据帧中存在的公共行 - Compare Dataframes Based on Column and Keep only common rows present in both dataframes 熊猫,比较索引和列替换位置中的2个数据框 - Pandas, compare 2 dataframes in index and column displaced location 根据列值比较大熊猫中的2个数据框 - Compare 2 dataframes in pandas based on column value 使用 pandas 比较两个数据帧的列值 - Compare column values of two dataframes using pandas 熊猫:将具有相同列名但计算方式不同的数据框组合 - Pandas: Combining dataframes with same column names but different calculations 合并两个具有相同列名但在pandas中具有不同列数的数据帧 - Merging two dataframes with same column names but different number of columns in pandas 比较具有不同格式列值的两个数据框 - Compare two dataframes with different format column values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM