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?
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])
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?
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])