NumPy Where, Select and Nonzero Functions
NumPy provides several functions for conditional selection and locating
elements in arrays. The np.where() function selects values
or returns matching indices, np.select() applies multiple
conditions, and np.nonzero() identifies positions of
nonzero elements. In this lesson, you will learn how these functions
work and how to apply them to practical datasets.
1. Introduction to np.where()
The np.where() function supports conditional selection.
When supplied with a condition, it returns the indices where the
condition is True. When supplied with a condition and two choices,
it selects a value from one of the choices for each element.
Output:
The condition values > 30 is evaluated element by
element. The matching elements occur at indices 2 and 4.
Two Common Forms
np.where(condition)returns indices where the condition is True.np.where(condition, x, y)chooses elements fromxory.
2. Selecting Values with np.where()
When three arguments are supplied, np.where() returns
values from the second argument where the condition is True and
values from the third argument otherwise.
Output:
Replace Values Based on a Condition
Output:
In this example, values below 25 are replaced with 25, while all other values remain unchanged.
np.where() returns a new result.
It does not modify the original array unless you explicitly assign
the result back to that array.
3. Understanding np.select()
The np.select() function is useful when there are multiple
conditions and each condition needs a different output value. It accepts
a list of conditions, a corresponding list of choices, and an optional
default value.
Output:
NumPy checks the conditions in order. When multiple conditions are True for an element, the choice associated with the first matching condition is used.
marks >= 85 before
marks >= 70, otherwise high marks could be classified
by the less specific condition first.
4. Applying Multiple Conditions with np.select()
Multiple conditions can classify data into categories. This is useful for grading, pricing rules, performance levels, and threshold-based data processing.
Output:
| Sales Range | Category |
|---|---|
| 1,500 and above | High |
| 700 to 1,499 | Medium |
| 400 to 699 | Low |
| Below 400 | Very Low |
The conditions are evaluated in their listed order, so the first matching choice determines the output for each element.
5. Introduction to np.nonzero()
The np.nonzero() function returns the indices of elements
that are not equal to zero. For a one-dimensional array, it returns
a tuple containing one index array.
Output:
Every nonzero element is included, regardless of whether it is positive or negative.
Output:
6. Finding Nonzero Positions in Two-Dimensional Arrays
For multidimensional arrays, np.nonzero() returns one
index array for each dimension. These arrays describe the coordinates
of every nonzero element.
Output:
Each nonzero element has a row coordinate and a column coordinate.
7. Counting Nonzero Elements
The np.count_nonzero() function counts elements that
are not equal to zero. You can count all nonzero elements or count
them along a specified axis.
Output:
| Expression | Meaning |
|---|---|
np.count_nonzero(array) |
Counts all nonzero elements. |
np.count_nonzero(array, axis=0) |
Counts nonzero values in each column. |
np.count_nonzero(array, axis=1) |
Counts nonzero values in each row. |
8. Understanding np.argwhere()
The np.argwhere() function returns the coordinates of
elements satisfying a condition, arranged as rows in a two-dimensional
array. It is convenient when you want each coordinate grouped together.
Output:
Each output row contains the coordinates of one matching element.
For example, coordinate [1, 1] refers to the value 50.
np.nonzero() returns a tuple
of index arrays, while np.argwhere() returns an array
of grouped coordinates. Choose the form that best fits your task.
9. Comparing Where, Select, Nonzero, and Argwhere
| Function | Main Purpose | Typical Result |
|---|---|---|
np.where() |
Return condition-based indices or choose between alternatives. | Indices or selected values. |
np.select() |
Choose results from multiple conditions. | Array of selected values. |
np.nonzero() |
Locate elements that are not zero. | Tuple of index arrays. |
np.count_nonzero() |
Count nonzero elements. | Integer or array of counts. |
np.argwhere() |
Return coordinates of elements satisfying a condition. | Array of grouped coordinates. |
np.where() for a condition and two alternatives,
np.select() for several conditions,
np.nonzero() for nonzero positions, and
np.count_nonzero() when you only need a count.
10. Practical Project: Student Result Classification
In this project, student marks will be classified into result
categories using np.select(). We will also locate
students who meet a target score using np.where().
Output:
Project Learning Outcomes
- Classify data using multiple conditions.
- Find qualifying records using
np.where(). - Keep names and marks aligned using matching indices.
- Use vectorized operations instead of manually checking every mark.
11. Common Mistakes and Best Practices
Using np.where() for Multiple Categories
Nested np.where() expressions can become difficult
to read. Use np.select() when several conditions
map to different choices.
Ignoring Condition Order
np.select() uses the choice corresponding to the
first True condition. Put more specific or higher-priority
conditions first.
Confusing Nonzero Values with Positive Values
np.nonzero() includes negative values as well as
positive values. It excludes zero, not negative numbers.
Confusing Coordinate Formats
np.nonzero() returns one index array per dimension,
while np.argwhere() groups coordinates into rows.
Forgetting Array Shapes
Ensure conditions and choices are compatible with the array shapes. NumPy uses broadcasting where supported, but incompatible shapes can raise an error.
12. Practice Exercises
Exercise 1: Find Matching Indices
Create an array of integers and use np.where() to
find the indices of values greater than 50.
Exercise 2: Conditional Replacement
Use np.where() to replace all negative values in an
array with zero.
Exercise 3: Multiple Categories
Use np.select() to classify marks as Excellent,
Pass, or Fail.
Exercise 4: Nonzero Positions
Create an array containing zero and nonzero values. Use
np.nonzero() to find all nonzero positions.
Exercise 5: Matrix Coordinates
Create a two-dimensional array and use np.argwhere()
to find coordinates of values greater than 25.
Exercise 6: Count Nonzero Elements
Use np.count_nonzero() to count nonzero values in
the complete matrix and separately in each row.
Summary
In this lesson, you learned to use np.where() to find
matching indices and choose values based on a condition. You also
explored np.select() for multiple conditional choices
and learned how condition order affects the selected result.
You practiced locating nonzero elements with np.nonzero(),
counting them with np.count_nonzero(), and retrieving
grouped coordinates with np.argwhere(). These functions
help classify, filter, locate, and analyze values efficiently in
one-dimensional and multidimensional arrays.