How to overload & (and) clauses filtering Numpy arrays?

Question:

pseudo i.e.:

A = np.array(...)

conditions = [(A > 1), (A < 2)]                         # how to do something like these?

filtered = A[&(condition for condition in conditions)]  #

With few conditions, it’s ok to go by, for example, filtered = A[(A > 1) & (A < 2)]; though is it possible to do so in a more scalable way?

Asked By: L. B.

||

Answers:

Let’s try np.logical_and with an unpacking operator on the list of conditions.

arr = np.random.random((10,))
conditions = [arr>0.2, arr**2<=0.5] #list of conditions
arr[np.logical_and(*conditions)]    #unpack conditions inside logical_and with *
array([0.33208271, 0.22984103, 0.58209428, 0.37531787, 0.69639457])
Answered By: Akshay Sehgal
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.