代码之家  ›  专栏  ›  技术社区  ›  Andy Wang

无法检查数组中的任何项是否也在另一个数据帧中

  •  1
  • Andy Wang  · 技术社区  · 7 年前

    我已经创建了一个数据框架 c 和数组 b . 我已经成功地检查了 c 也在 b .

    a = np.array([
                    [2.,1.,1.],
                    [3.,4.,1.],
                    [5.,6.,1.],
                    [7.,8.,1.]])
    
    c = pd.DataFrame(data=a,
                     dtype = 'float64')
    
    
    b = np.array(([1, 10, 5, 2]), dtype = 'float64')
    
    for i in range(len(c)):
        if c.iloc[i,0] in b:
            print ("Great")
        else:
            print ('sad')
    

    输出:

    Great
    sad
    Great
    sad
    

    但是,当检查b中的任何项是否在c数据帧中时,以下操作不起作用。为什么会这样?

    for i in range(len(b)):
        if b[i,0] in c:
            print ('hola')
        else:
            print ('False')
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   jezrael    7 年前

    我认为最好是避免循环,因为速度慢。因此,对于按数组检查列,请使用 Series.isin :

    mask1 = c[0].isin(b)
    print (mask1 )
    0     True
    1    False
    2     True
    3    False
    Name: 0, dtype: bool
    
    d1 = np.where(mask1, 'Great', 'sad')
    print (d1)
    ['Great' 'sad' 'Great' 'sad']
    

    对于检查所有值,请使用 DataFrame.isin 具有 any 检查是否至少有一个 True 中的每行 boolean DataFrame :

    mask2 = c.isin(b).any(axis=1)
    print (mask2)
    0    True
    1    True
    2    True
    3    True
    dtype: bool
    
    e1 = np.where(mask2, 'hola', 'False')
    print (e1)
    ['hola' 'hola' 'hola' 'hola']
    

    详细信息:

    print (c.isin(b))
           0      1     2
    0   True   True  True
    1  False  False  True
    2   True  False  True
    3  False  False  True
    

    如果需要检查 b 在里面 c 使用 numpy.in1d 数据帧的平展值为 1d array 通过 numpy.ravel :

    mask3 = np.in1d(b, c.values.ravel())
    print (mask3)
    [ True False  True  True]