Check if column value is in other columns in pandas

后端 未结 5 1732
终归单人心
终归单人心 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:26

    You can use drop, isin and any.

    • drop the target column to have a df with your A, B, C columns only
    • check if the values isin the target column
    • and check if any hits are present

    That's it.

    df["exists"] = df.drop("target", 1).isin(df["target"]).any(1)
    print(df)
    
        target  A       B       C       exists
    0   cat     bridge  cat     brush   True
    1   brush   dog     cat     shoe    False
    2   bridge  cat     shoe    bridge  True
    

提交回复
热议问题