Check if column value is in other columns in pandas

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

    you can use apply a function for each row that counts the number of value that match the value in the 'target' column:

    df["exist"] = df.apply(lambda row:row.value_counts()[row['target']] > 1 , axis=1)
    

    for a dataframe that looks like:

       b  c target
    0  3  a      a
    1  3  4      2
    2  3  4      2
    3  3  4      2
    4  3  4      4
    

    the output will be:

       b  c target  exist
    0  3  a      a   True
    1  3  4      2  False
    2  3  4      2  False
    3  3  4      2  False
    4  3  4      4   True
    

提交回复
热议问题