1

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 every columns of M with v, i.e. I want a matrix with the first column consisting of True, True, True. A second saying False, True, False. A third True, False, False.

How do I achieve this? Thanks!

3 Answers 3

5

Use broadcasted comparison:

>>> M == v[:, None]
array([[ True, False,  True],
       [ True,  True, False],
       [ True, False, False]])
Sign up to request clarification or add additional context in comments.

1 Comment

No, now it is OK
0

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.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.