Numpy: Filtering rows by multiple conditions?

18,227

Solution 1

you can use multiple filters in a slice, something like this:

x = np.arange(90.).reshape(30, 3)
#set the first 10 rows of cols 1,2 to be zero
x[0:10, 0:2] = 0.0
x[(x[:,0] == 0.) & (x[:,1] == 0.) & (x[:,2] > 10)]
#should give only a few rows
array([[  0.,   0.,  11.],
       [  0.,   0.,  14.],
       [  0.,   0.,  17.],
       [  0.,   0.,  20.],
       [  0.,   0.,  23.],
       [  0.,   0.,  26.],
       [  0.,   0.,  29.]])

Solution 2

How about this -

meta[meta[:,2]<X * np.all(meta[:,0:2]==0,1),:]

Sample run -

In [89]: meta
Out[89]: 
array([[ 1,  2,  3,  4],
       [ 0,  0,  2,  0],
       [ 9,  0, 11, 12]])

In [90]: X
Out[90]: 4

In [91]: meta[meta[:,2]<X * np.all(meta[:,0:2]==0,1),:]
Out[91]: array([[0, 0, 2, 0]])
Share:
18,227

Related videos on Youtube

sten
Author by

sten

Updated on June 04, 2022

Comments

  • sten
    sten almost 2 years

    I have a two-dimensional numpy array called meta with 3 columns.. what I want to do is :

    1. check if the first two columns are ZERO
    2. check if the third column is smaller than X
    3. Return only those rows that match the condition

    I made it work, but the solution seem very contrived :

    meta[ np.logical_and( np.all( meta[:,0:2] == [0,0],axis=1 ) , meta[:,2] < 20) ]
    

    Could you think of cleaner way ? It seem hard to have multiple conditions at once ;(

    thanks


    Sorry first time I copied the wrong expression... corrected.

    • Joran Beasley
      Joran Beasley
      that doesnt work ... it will fail when both cases are false
    • Mazdak
      Mazdak
      how it works with ==? you need numpy.logical_and