1

How do I select rows of a matrix with a specific condition using np indexing?

My matrix is

n = np.array([[1,2],[4,5], [1,22]])

and I would like to select the rows whose first element is greater than one. Something similar to:

n[lambda x: x[0] > 1]

2 Answers 2

3

Edit: np.where is optional, thanks @user2357112.

n[n[:, 0] > 1]

Try

n[np.where(n[:, 0] > 1)]

where np.where returns an array of row indices that satisfy the given condition.

Sign up to request clarification or add additional context in comments.

2 Comments

Don't use np.where. Any indexing of the form x[np.where(whatever)] can be replaced with x[whatever], and the code will be equivalent, more concise, and more efficient.
@user2357112 funny, I thought that returned an error. Thanks!
2

You can use:

n[n[:,0] > 0, :]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.