Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

python - Check if column value is in other columns in pandas

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   bridge

How do I test whether df.target is in any of the columns ['A','B','C', etc.], where there are many columns to check?

I have tried merging A,B and C into a string to use df.abcstring.str.contains(df.target) but this does not work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...