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)
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)
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])
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With