Skip to content

How to select rows using multiple Boolean conditions in NumPy (with Code)

The Short Answer (TL;DR)

Build a one-dimensional Boolean mask with one element per row, combine parenthesized comparisons with & and |, and apply that mask as array[mask]. Keep original row positions when the selected records need an audit trail.

import numpy as np
x = np.array([[5.,.9],[10.,.8],[20.,.7],[30.,.95]])
print(x[(x[:,0]>=10)&(x[:,0]<30)&(x[:,1]>=.8)])

Detailed Implementation

This example uses synthetic data and does not need a network connection. Install the recorded package versions in a separate Python environment before running it.

python -m pip install numpy==2.5.4
from pathlib import Path
import numpy as np

def select_records(values,lower=10.0,upper=30.0,min_score=0.8):
    raw=np.asarray(values)
    if raw.ndim!=2 or raw.shape[1]!=3 or raw.dtype.kind not in "iuf":
        raise ValueError("Require a real numeric matrix: amount, score, priority.")
    if (not np.isfinite([lower,upper,min_score]).all()
            or lower>=upper or not 0<=min_score<=1):
        raise ValueError("Require finite ordered amount limits and a score threshold in [0,1].")
    x=raw.astype(np.float64,copy=False)
    amount,score,priority=x[:,0],x[:,1],x[:,2]
    if np.any(np.isfinite(score)&((score<0)|(score>1))):
        raise ValueError("Observed finite scores must be in [0,1].")
    if np.any(np.isfinite(priority)&~np.isin(priority,[0,1])):
        raise ValueError("Observed finite priority codes must be 0 or 1.")
    finite=np.isfinite(x).all(axis=1)
    amount_ok=(amount>=lower)&(amount<upper)
    score_or_priority=(score>=min_score)|(priority==1)
    mask=finite&amount_ok&score_or_priority
    positions=np.flatnonzero(mask)
    audit={"input_rows":len(x),"finite_rows":int(finite.sum()),
           "nonfinite_rows":int((~finite).sum()),"selected_rows":len(positions),
           "selected_fraction_of_input":len(positions)/len(x) if len(x) else np.nan}
    return x[mask],positions,mask,audit

# Identical values at positions 1 and 9 are separate source records.
data=np.array([[5.,.95,1.],[10.,.8,0.],[20.,.7,1.],[30.,.99,1.],
               [25.,np.nan,1.],[15.,.9,0.],[20.,.6,0.],[np.nan,.99,1.],
               [12.,.5,np.nan],[10.,.8,0.]])
selected,positions,mask,audit=select_records(data)
source_ids=np.array([f"row-{i}" for i in range(len(data))])
text=("SELECTED SOURCE IDS\n"+str(source_ids[positions].tolist())+"\nSELECTED VALUES\n"+
      np.array2string(selected)+"\n"+"\n".join(f"{k}={v}" for k,v in audit.items())+"\n")
Path("multiple-conditions-row-selection.txt").write_text(text,encoding="utf-8")
print(text)

Selected source IDs are row-1, row-2, row-5 and row-9. The selected matrix has shape (4, 3), and both identical rows are retained. The audit reports ten input rows, seven finite rows, three nonfinite rows and an input selection fraction of 0.4.

How do & and | combine row conditions?

The full rule requires a finite row, an amount at least 10 but below 30, and either a score at least 0.8 or priority code 1. The amount interval and finite-data policy always apply; priority changes only the score requirement. Parentheses keep each comparison and alternative explicit. Python and/or are scalar truth operators and do not implement this elementwise combination of Boolean arrays.

Why must the mask have one element per row?

Each column comparison produces a vector of length equal to the number of records. Combining those vectors leaves one decision for each record, and x[mask] retains all three columns for selected rows. Applying a full two-dimensional mask instead selects individual elements and returns a different layout. The checks confirm that this mask has shape (10,) and Boolean dtype before interpreting the selected rows.

How are missing values and interval boundaries handled?

The policy requires all three fields to be finite. A row with a missing score is therefore excluded even when its priority is 1; the priority alternative does not override the completeness requirement. A source amount of exactly 10 passes, while exactly 30 fails. Missing, positive-infinite and negative-infinite values fail the finite-row mask. Finite scores outside [0,1] and finite priority codes other than 0 or 1 are rejected as schema violations.

Which records are selected, including repeated values?

Source positions 1, 2, 5 and 9 satisfy the rule. Positions 1 and 9 contain identical values, but they remain two separate observations with different source IDs. Boolean selection does not deduplicate them or reorder their positions. The returned positions connect each selected record to its source. If rows are reordered before selection, carry stable identifiers through that operation rather than treating new positional indices as original IDs.

Does Boolean extraction produce a writable view of the source?

Boolean indexing is advanced indexing and returns a copy of the selected data. The memory-overlap and mutation checks confirm that editing an extracted result does not edit this source matrix. An assignment made directly as data[mask] = value is a different operation and writes into data. The implementation only extracts rows. It leaves the source values, duplicate records and missing fields unchanged.

Which denominator belongs in a selection rate?

Four of the ten input rows are selected, giving a 40 percent selection fraction of input. Seven rows are finite, so a fraction restricted to complete rows would instead be four divided by seven. Those denominators answer different questions and should be labeled. An empty input has no defined input selection fraction. This constructed rule is a filtering policy, not evidence that excluded observations are inaccurate or that the selected subset represents a population.

Mathematical Context

Let F_i indicate that every required field in row i is finite, A_i indicate 10 <= amount_i < 30, S_i indicate score_i >= 0.8, and P_i indicate priority_i = 1. The selection indicator is F_i AND A_i AND (S_i OR P_i). Its sum is four for this ten-row fixture. Dividing that count by ten gives the input selection fraction 0.4. The finite count is seven, so a complete-row selection fraction would have a different denominator. Logical indicators and fractions are dimensionless; the amount bounds use the same units as the amount column.

\[ M_i=F_i\wedge A_i\wedge(S_i\vee P_i),\qquad r=\frac{\sum_i M_i}{N},\quad N>0 \]

Reproducibility

Executed with Python 3.12.14; numpy 2.5.4. Automated checks confirm the stated output properties.

Primary documentation

Related guides