Compare Columns Of Numpy Matrix With Array
I have a numpy matrix and want to compare every columns to a given array, like: M = np.array([1,2,3,3,2,1,1,3,2]).reshape((3,3)).T v = np.array([1,2,3]) Now I want to compare ever
Solution 1:
Use broadcasted comparison:
>>> M == v[:, None]
array([[ True, False, True],
[ True, True, False],
[ True, False, False]])
Solution 2:
You might consider using np.equal
column-wise:
np.array([np.equal(col, v) for col in M.T]).T
it compares the elements of two numpy arrays element-wise. The M.T
makes for loop to pop your original M
columns as one-dimensional arrays and the final transpose is needed to reverse it.
Here the equal/not_equal functions are described.
Solution 3:
Alternatively, you could match each row in the matrix with the given vector using np.apply_along_axis
>>> M
array([[1, 3, 1],
[2, 2, 3],
[3, 1, 2]])
>>> v
array([1, 2, 3])
>>> np.apply_along_axis(lambda x: x==v, 1, M)
array([[ True, False, False],
[False, True, True],
[False, False, False]], dtype=bool)
Post a Comment for "Compare Columns Of Numpy Matrix With Array"