meto
meto

Reputation: 3719

Numpy advanced indexing on a matrix given a condition

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]

Upvotes: 1

Views: 181

Answers (2)

gauteh
gauteh

Reputation: 17195

You can use:

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

Upvotes: 2

jayelm
jayelm

Reputation: 7657

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.

Upvotes: 3

Related Questions