Check if column value is in other columns in pandas

后端 未结 5 1748
终归单人心
终归单人心 2020-12-17 18:01

I have the following dataframe in pandas

  target   A       B      C
0 cat      bridge  cat    brush  
1 brush    dog     cat    shoe
2 bridge   cat     shoe         


        
5条回答
  •  醉酒成梦
    2020-12-17 18:30

    You can use eq, for drop column pop if neech check by rows:

    mask = df.eq(df.pop('target'), axis=0)
    print (mask)
           A      B      C
    0  False   True  False
    1  False  False  False
    2  False  False   True
    

    And then if need check at least one True add any:

    mask = df.eq(df.pop('target'), axis=0).any(axis=1)
    print (mask)
    0     True
    1    False
    2     True
    dtype: bool
    
    df['new'] = df.eq(df.pop('target'), axis=0).any(axis=1)
    print (df)
            A     B       C    new
    0  bridge   cat   brush   True
    1     dog   cat    shoe  False
    2     cat  shoe  bridge   True
    

    But if need check all values in column use isin:

    mask = df.isin(df.pop('target').values.tolist())
    print (mask)
           A      B      C
    0   True   True   True
    1  False   True  False
    2   True  False   True
    

    And if want check if all values are True add all:

    df['new'] = df.isin(df.pop('target').values.tolist()).all(axis=1)
    print (df)
            A     B       C    new
    0  bridge   cat   brush   True
    1     dog   cat    shoe  False
    2     cat  shoe  bridge  False
    

提交回复
热议问题