Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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.

like image 223
Q Yang Avatar asked Jul 10 '18 03:07

Q Yang


4 Answers

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)

https://ideone.com/YmWtlv

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]

Note

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)
like image 101
Mad Physicist Avatar answered Nov 11 '22 17:11

Mad Physicist


using a list comprehension and zip

arr = np.array([[1, 2],[3, 4],[2, 5]])
a = np.array([2,5,2])

[y in x for x, y in zip(arr, a)]
# outputs: [True, False, True]

Using np.any with axis=1:

np.any(arr == a[:, None], axis=1)
# outputs: array([ True, False,  True])
like image 43
Haleemur Ali Avatar answered Nov 11 '22 19:11

Haleemur Ali


This one-liner should do it. It works for any number of columns, too.

# Set up
import numpy as np
array = np.array([[1, 2],[3, 4],[2, 5]])
vector = np.array([2,5,2])

# Solution
result = np.logical_or.reduce(array == vector[:,None], 1)

Output:

[ True, False,  True]

This compares all of the elements against the column vector vector and then reduces over rows.

like image 23
Alex Reinking Avatar answered Nov 11 '22 18:11

Alex Reinking


We can also make use of broadcasting and the dot product.

a = np.array([[1, 2], [3, 4], [2, 5]])
b = np.array([2, 5, 2]) 

Solution

(a == b[:,None]) @ np.array([1, 1]).astype(bool) 
like image 37
Tai Avatar answered Nov 11 '22 17:11

Tai