CSLearner
CSLearner

Reputation: 259

How can I isolate rows in a 2d numpy matrix that match a specific criteria?

How can I isolate rows in a 2d numpy matrix that match a specific criteria? For example if I have some data and I only want to look at the rows where the 0 index has a value of 5 or less how would I retrieve those values?

I tried this approach:

import numpy as np

data = np.matrix([
    [10, 8, 2],
    [1, 4, 5],
    [6, 5, 7],
    [2, 2, 10]])

#My attempt to retrieve all rows where index 0 is less than 5
small_data = (data[:, 0] < 5)

The output is:

matrix([
    [False],
    [ True],
    [False],
    [ True]], dtype=bool)

However I'd like the output to be:

   [[1, 4, 5],
    [2, 2, 10]]

Another approach may be for me to loop through the matrix rows and if the 0 index is smaller than 5 append the row to a list but I am hoping there is a better way than that.

Note: I'm using Python 2.7.

Upvotes: 0

Views: 310

Answers (3)

saloua
saloua

Reputation: 2493

That way you got a logical array that you can use to select the desired rows.

>>> data = np.matrix([
[10, 8, 2],
[1, 4, 5],
[6, 5, 7],
[2, 2, 10]])
>>> data = np.array(data)
>>> data[(data[:, 0] < 5), :]
array([[ 1,  4,  5],
   [ 2,  2, 10]])

You can also use np.squeeze to filter the rows.

>>> ind = np.squeeze(np.asarray(data [:,0]))<5
>>> data[ind,:]
array([[ 1,  4,  5],
   [ 2,  2, 10]])

Upvotes: 1

MSeifert
MSeifert

Reputation: 152657

First: Don't use np.matrix, use normal np.arrays.

import numpy as np

data = np.array([[10, 8, 2],
                 [1, 4, 5],
                 [6, 5, 7],
                 [2, 2, 10]])

Then you can always use boolean indexing (based on the boolean array you get when you do comparisons) to get the desired rows:

>>> data[data[:, 0] < 5]
array([[ 1,  4,  5],
       [ 2,  2, 10]])

or integer array indexing:

>>> data[np.where(data[:, 0] < 5)]
array([[ 1,  4,  5],
       [ 2,  2, 10]])

Upvotes: 2

Jay Parikh
Jay Parikh

Reputation: 2489

use the following code.

data[data[small_data,:]]

That would work

Upvotes: -2

Related Questions