1

Consider the following 2d array:

>>> A = np.arange(2*3).reshape(2,3)
array([[0, 1, 2],
       [3, 4, 5]])

>>> b = np.array([1, 2])

I would like to get the following mask from A as row wise condition from b as an upper index limit:

>>> mask
array([[True, False, False],
       [True, True, False]])

Can numpy do this in a vectorized manner?

2 Answers 2

3

You can use array broadcasting:

mask = np.arange(A.shape[1]) < b[:,None]

output:

array([[ True, False, False],
       [ True,  True, False]])
Sign up to request clarification or add additional context in comments.

Comments

0

Another possible solution, based on the idea that the wanted mask corresponds to a boolean lower triangular matrix:

mask = np.tril(np.ones(A.shape, dtype=bool))

Output:

array([[ True, False, False],
       [ True,  True, False]])

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.