简体   繁体   English

检查列值是否在pandas的其他列中

[英]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? 如何测试df.target是否在任何列['A','B','C', etc.] ,哪些列要检查?

I have tried merging A,B and C into a string to use df.abcstring.str.contains(df.target) but this does not work. 我尝试将A,B和C合并为字符串以使用df.abcstring.str.contains(df.target)但这不起作用。

You can use drop , isin and any . 你可以使用dropisinany

  • drop the target column to have a df with your A , B , C columns only drop target列,使其仅包含ABC列的df
  • check if the values isin the target column 检查值isin目标列
  • and check if any hits are present 并检查是否有any命中

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

OneHotEncoder approach: OneHotEncoder方法:

In [165]: x = pd.get_dummies(df.drop('target',1), prefix='', prefix_sep='')

In [166]: x
Out[166]:
   bridge  cat  dog  cat  shoe  bridge  brush  shoe
0       1    0    0    1     0       0      1     0
1       0    0    1    1     0       0      0     1
2       0    1    0    0     1       1      0     0

In [167]: x[df['target']].eq(1).any(1)
Out[167]:
0    True
1    True
2    True
dtype: bool

Explanation: 说明:

In [168]: x[df['target']]
Out[168]:
   cat  cat  brush  bridge  bridge
0    0    1      1       1       0
1    0    1      0       0       0
2    1    0      0       0       1

You can use eq , for drop column pop if neech check by rows: 如果neech按行检查,你可以使用eq ,drop drop pop

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 : 然后如果需要检查至少一个True添加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 : 但如果需要检查列使用中的所有值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 : 如果想检查所有值是否为True添加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

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

Another approach using index difference method: 另一种使用索引差异法的方法:

matches = df[df.columns.difference(['target'])].eq(df['target'], axis = 0)

#       A      B      C
#0  False   True  False
#1  False  False  False
#2  False  False   True

# Check if at least one match:
matches.any(axis = 1)

#Out[30]: 
#0     True
#1    False
#2     True

In case you wanted to see which columns meet the target, here is a possible solution: 如果您想查看哪些列符合目标,这是一个可能的解决方案:

matches.apply(lambda x: ", ".join(x.index[np.where(x.tolist())]), axis = 1)

Out[53]: 
0    B
1     
2    C
dtype: object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM