检查列值是否在pandas的其他列中 [英] Check if column value is in other columns in pandas
本文介绍了检查列值是否在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
我如何测试df.target
是否在要检查许多列的任何['A','B','C', etc.]
列中?
How do I test whether df.target
is in any of the columns ['A','B','C', etc.]
, where there are many columns to check?
我尝试将A,B和C合并为一个字符串以使用df.abcstring.str.contains(df.target)
,但这不起作用.
I have tried merging A,B and C into a string to use df.abcstring.str.contains(df.target)
but this does not work.
推荐答案
You can use drop
, isin
and any
.
-
drop
target
列仅包含A
,B
,C
列的df - 检查值
isin
是否为目标列 - 并检查是否存在
any
匹配项
drop
thetarget
column to have a df with yourA
,B
,C
columns only- check if the values
isin
the target column - and check if
any
hits are present
就是这样.
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
这篇关于检查列值是否在pandas的其他列中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文