Knowledge base / Python
numpy select: first match, boundaries and missing values
I explain condition priority, paired labels and NaN handling, including limits involving types, shapes and argument evaluation.

I want to give each number one of several categories. NumPy select accepts conditions and their corresponding results. The key rule is that when several conditions match, the first one in the list wins. An overly broad condition can capture values intended for a later exception.
I explain this using small synthetic data. The examples follow the NumPy 2.5 documentation and cover interval boundaries, unmatched values and missing data. Random input is unnecessary for understanding why the number 60 received the wrong label.
Conditions and results form pairs
numpy.select uses np.select(condlist, choicelist, default=0). The condition list contains Boolean masks; the choice list contains corresponding values or arrays. Both lists must have the same number of entries. The default is used wherever no condition is true.
I define three categories: low below 20, medium from 20 through 50 inclusive, and high above 50. Explicit boundaries prevent 20 and 50 from accidentally remaining unclassified. These decisions come from the task definition; select simply implements them.
import numpy as np
x = np.array([10, 20, 50, 60])
conditions = [x < 20, (x >= 20) & (x <= 50), x > 50]
choices = ["low", "medium", "high"]
labels = np.select(conditions, choices, default="unknown")
The labels are low, medium, medium and high. The first condition matches 10, the second includes both boundaries and the third matches 60. Each of the four positions receives one result. Here the intervals are disjoint, so their order does not change the assignments.
The first match wins when conditions overlap
Now I deliberately make the middle condition too broad:
bad_conditions = [x < 20, x >= 20, x > 50]
bad_labels = np.select(bad_conditions, choices, default="unknown")
The results are low, medium, medium and medium. For 60, both x >= 20 and x > 50 are true, but the earlier pair specifies medium. The documented rule selects the first matching condition rather than the most specific condition or the last assignment.
| Value | x < 20 | x >= 20 | x > 50 | Result of the incorrect variant |
|---|---|---|---|---|
| 10 | True | False | False | low |
| 20 | False | True | False | medium |
| 50 | False | True | False | medium |
| 60 | False | True | True | medium |
A high label for 60 would contradict this code because the earlier condition captures that value and selects medium. The precedence explanation and the result must tell the same story. A correct sentence below a snippet does not repair an incorrect result above it.
Reorder pairs rather than conditions alone
I can return to the disjoint intervals or give values above 50 priority:
priority_labels = np.select(
[x > 50, x < 20, x >= 20],
["high", "low", "medium"],
default="unknown",
)
The result is again low, medium, medium and high. I moved the condition together with its corresponding label. Reordering only conditions while retaining the earlier choices would introduce a different mapping error. I read the two lists as ordered pairs.
For more complex rules I write the priority in words: handle missing data first, then a special case, then ordinary cases. That helps a reader understand why one rule precedes another. I do not reorder conditions for an assumed speed benefit without checking whether the change also alters their meaning.

Handle missing values explicitly
For a numeric array containing NaN, I can add a missing category using np.isnan:
values = np.array([10.0, 60.0, np.nan])
with_missing = np.select(
[np.isnan(values), values < 20, values > 50],
["missing", "low", "high"],
default="medium",
)
The results are low, high and missing. The first condition recognises NaN, while the remaining conditions implement the example’s ranges. Here the default represents the middle interval for ordinary numbers. Comparing values == np.nan is not the way I detect missing values.
The example assumes a numeric array. Text, mixed object data and pandas.NA can require different preparation. This short expression is not a universal check for every missing representation in every source. I first establish the input type and allowed values, then construct the masks accordingly.
Results need compatible types and shapes
For text categories I supply a text default. Leaving the default numeric zero alongside string results can produce a type conflict in NumPy 2.x. I also do not want an absent category disguised as an ordinary numeric category. The type-promotion documentation explains the need for compatible result types.
The length of conditions and choices is a different question from the shape of each mask. Our masks have the same number of positions as x and our text choices are scalars. Array-valued choices must also satisfy broadcasting rules. Matching the number of branches does not establish that all data dimensions are compatible.
The result is a NumPy array without pandas index labels. When it comes from frame data, I ensure row order has not changed between creating the masks and assigning the result. In assign, an array is assigned positionally, unlike a Series aligned by labels.
Choosing a result does not defer argument evaluation
Rule precedence determines which value is selected, but does not guarantee lazy evaluation of expressions in choices. Call arguments are evaluated under Python’s rules before select receives them. A condition x != 0 does not by itself stop an argument written as 1 / x from being evaluated at zero positions.
I therefore do not use select as a shield for invalid calculations. First I prepare values according to their valid domain, then choose the result. For two possible outcomes, np.where may be clearer; it also does not promise lazy evaluation of its arguments.
I avoid a universal performance ranking between where and select. I choose based on the number of branches and clarity of the rules. Actual time also depends on mask construction, data size and the cost of expressions used to prepare the candidate results.
Exercise: inspect boundaries and priorities
Add 19, 21, 49 and 51 to the first array. Assign labels manually from the interval definitions. Then reason through the incorrect version with broad x >= 20 and identify which values lose their high category. This examines precedence without relying on a lucky random sample.
Finally exchange two condition-and-label pairs. Should the result change for disjoint intervals, and should it change for overlapping ones? I consider the classification understandable when I can explain both situations and identify where missing and unmatched values will go.
Key takeaways
What happens when two conditions match?
numpy.select chooses the result paired with the first true condition in the list.
Can I reorder only the conditions?
Their corresponding labels must move with them. Reorder complete condition-and-result pairs.
Does a condition prevent evaluation of an invalid branch?
It does not guarantee lazy argument evaluation. Expressions supplied in choices are prepared before the result is selected.
AI was used in an automated way while working on this article. If you want to learn how to do it too, check out this project.
