filtering numpy matrix on a column

Viewed 15293

I have a numpy matrix as follows:

data = np.matrix(
      "5 3 1;"
      "4 4 1;"
      "6 4 1;"
      "8 2 1;"
      "3 5 1;"
      "1 7 1;"
      "5 4 1;"
      "0 1 0;"
      "2 0 0")
# Output:
matrix([[5, 3, 1],
    [4, 4, 1],
    [6, 4, 1],
    [8, 2, 1],
    [3, 5, 1],
    [1, 7, 1],
    [5, 4, 1],
    [0, 1, 0],
    [2, 0, 0]])

what I want is to filter the matrix on the third column whose value is 1; that is, I do not want to get the rows whose 3rd value is 0. In short, I want to extract the matrix below:

matrix([[5, 3, 1],
    [4, 4, 1],
    [6, 4, 1],
    [8, 2, 1],
    [3, 5, 1],
    [1, 7, 1],
    [5, 4, 1]])

I tried a few combinations to filter it; but none of them worked for me. For instance, the following code rules out the rows with zero, but it returns only the first column.

data[data[:,2]>0]
#Output: 
matrix([[5, 4, 6, 8, 3, 1, 5]])

Is there a way to filter this matrix without explicitly writing loop statements?

4 Answers

I've just learnt about the np.where function and applied on this task. This solution preserves the type of the original data.

a = np.matrix([[5, 3, 1],
 [4, 4, 1],
 [6, 4, 1],
 [8, 2, 1],
 [3, 5, 1],
 [1, 7, 1],
 [5, 4, 1],
 [0, 1, 0],
 [2, 0, 0]])
row_ndx,_ = np.where(a[:,2]>0)
a[row_ndx]

or a oneliner:

a[np.where(a[:,2]>0)[0]]
Related