Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy: Filtering rows by multiple conditions?

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.

like image 793
sten Avatar asked Apr 07 '15 21:04

sten


People also ask

How do you filter multiple conditions in Python?

Using Loc to Filter With Multiple ConditionsAdd each condition you want to be included in the filtered result and concatenate them with the & operator. You'll see our code sample will return a pd. dataframe of our filtered rows. Don't forget to include "import pandas as pd" at the top!

What does .all do in Numpy?

all() in Python. The numpy. all() function tests whether all array elements along the mentioned axis evaluate to True.

How we can filter values evaluate values in Numpy arrays?

In NumPy, you filter an array using a boolean index list. A boolean index list is a list of booleans corresponding to indexes in the array. If the value at an index is True that element is contained in the filtered array, if the value at that index is False that element is excluded from the filtered array.

How do you make a boolean mask in Python?

To create a boolean mask from an array, use the ma. make_mask() method in Python Numpy. The function can accept any sequence that is convertible to integers, or nomask. Does not require that contents must be 0s and 1s, values of 0 are interpreted as False, everything else as True.


1 Answers

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.]])
like image 120
reptilicus Avatar answered Oct 18 '22 17:10

reptilicus