pythonnumpysearchconditional-statementswhere-clause

numpy.where build conditional filter in python


How do I build a numpy filter, adding each filter element depending on logic, rather than initiating the entire filter at once?

I want to build a filter like this:

filter = []
IF A == 0:
   filter.append(np.where(a>0))
ELSE:
   filter.append(np.where(b>0))

As opposed to this.

filtered_values = np.where(
            (dataFrame['a'] > 0) &
            (dataFrame['b'] > 0))


Solution

  • You can start with a filter of all True, then add the other conditions based on the value of A like so:

    f = np.full(len(a), True)
    
    if A == 0:
        f &= a > 0
    else:
        f &= b > 0