【问题标题】:Check if rows of one DataFrame are present in another检查一个 DataFrame 的行是否存在于另一个 DataFrame 中
【发布时间】:2019-05-15 04:50:11
【问题描述】:

我有两个数据框:

DF1

 A   B
'a' 'x' 
'b' 'y'
'c' 'z'

DF2

Col1 Col2
'j'  'm'
'a'  'x'
'k'  'n'
'b'  'y'

并且想查找 DF1 的行是否包含在 DF2 中,并将该列 Bool_col 添加到 DF1,如下所示。

DF1

 A   B   Bool_col
'a' 'x'  True
'b' 'y'  True
'c' 'z'  False

我尝试在 Col1 和 Col2 的串联列表中查找 A 和 B 的串联,但我的数据给我带来了意想不到的麻烦。有关如何在不连接列的情况下执行此操作的任何帮助?

【问题讨论】:

  • mergeindicator

标签: python pandas


【解决方案1】:

使用pandas.mergenumpy.where

df = df1.merge(df2, how='left', indicator=True, left_on=['A','B'], right_on=['Col1','Col2'])
df['Bool_col'] = np.where(df['_merge']=='both', True, False)
df.drop(['_merge','Col1','Col2'], 1, inplace=True)
print(df)

输出:

   A  B     Bool_col
0  a  x      True
1  b  y      True
2  c  z     False

编辑

根据 cmets 中的@cs95 建议,这里不需要np.where。 你可以简单地做

df1['Bool_col'] = df['_merge']=='both'
# df.drop(['_merge','Col1','Col2'], 1, inplace=True)

【讨论】:

  • 这没有错,但它比它需要的更笨重。
  • @cs95 我仍在弄清楚.eval 在您的回答中做了什么。你能详细说明一下吗?
  • eval 可以方便地将多行压缩为一条。通常要对列执行条件,您需要将结果存储为变量并在后续语句中访问结果列。使用 eval,您可以使用字符串评估 do this dynamically
  • PS:我所指的笨拙部分是df['Bool_col'] = np.where(df['_merge']=='both', True, False),它可能只是df['Bool_col'] = df['_merge']=='both'。您也可以将结果分配给df1,而不是创建df 并删除列。
  • 现在看起来好多了,但您仍然应该/也考虑分配回 df1。一般来说,df2 的列可能比 col1 和 col2 的列更多,因此在此处删除可能就足够了,也可能不够。
【解决方案2】:

mergeindicator 参数一起使用,然后检查哪些行显示“两者”。

df1['Bool_col'] = (df1.merge(df2, 
                             how='left', 
                             left_on=['A', 'B'], 
                             right_on=['Col1', 'Col2'], 
                             indicator=True)
                      .eval('_merge == "both"'))

df1
     A    B  Bool_col
0  'a'  'x'      True
1  'b'  'y'      True
2  'c'  'z'     False

【讨论】:

    猜你喜欢
    • 2021-01-17
    • 2021-11-12
    • 1970-01-01
    • 2019-10-09
    • 2019-02-22
    • 1970-01-01
    • 2020-10-16
    • 2021-01-17
    • 1970-01-01
    相关资源
    最近更新 更多