How to perform contain operation between a numpy array and a vector row-wise?

  • A+

Now I have a numpy array,

[[1 2]  [3 4]  [2 5]] 

and a vector.

[2,  5,  2] 

I want to perform a contain operation between the array and the vector row wise. In other words, I want to check whether the first row [1, 2]contain 2, whether the second row [3, 4] contain 5. The expected output would look like:

[True, False, True]  

How could I implement this function? Many thanks in advance.


You can broadcast the vector into a column, equate it to all the elements in the rows of the matrix, and see if any element is True in each row:

import numpy as np  a = np.array(     [[1, 2],      [3, 4],      [2, 5]]) v = np.array([2, 5, 2]).reshape(-1, 1)  np.any(a == v, axis=1)

reshape turns your 1D (row) vector into a column vector. This is necessary because normally broadcasting lines up the shapes along the right, so you need an explicit trailing dimension of 1. Another way to accomplish the same thing is to use newaxis (a.k.a. None):

v = np.array([2, 5, 2])[..., np.newaxis] 


My original answer suggested reduce using logical_or, which is just a more complicated way of saying any:

np.logical_or.reduce(a == v, axis=1) 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: