Python:NumPy .where()
Anonymous contributor
Published May 11, 2025
Contribute to Docs
The .where() function is a built-in method in NumPy used for conditional selection of elements in arrays. It returns elements based on a condition:
- When only the condition is provided,
.where()returns the indices where the condition isTrue. - When all three arguments are provided i.e. condition, x, and y, it returns an array where elements from
xare selected where the condition isTrue, and elements fromyare selected where the condition isFalse.
Syntax
numpy.where(condition[, x, y])
Parameters:
condition: A boolean array or condition expression. Elements that evaluate toTruewill take values fromx, and elements that evaluate toFalsewill take values fromy.x(optional): The array or value to be selected when the condition isTrue.y(optional): The array or value to be selected when the condition isFalse.
Return value:
- When all three arguments are provided, it returns an array with elements taken from
xwhere the condition isTrue, and elements taken fromywhere the condition isFalse. - When only the condition is provided, it returns the indices where the condition is
True.
Example
The following example demonstrates how to use the .where() function with the parameters:
import numpy as nparr = np.array([10, 15, 20, 25, 30])# Get the indices where elements are greater than 20indices = np.where(arr > 20)print(indices)# Use condition to select values from two arraysresult = np.where(arr > 20, "big", "small")print(result)
This example results in the following output:
(array([3, 4]),)['small' 'small' 'small' 'big' 'big']
Codebyte example
Run the following codebyte example better to understand the .where() function:
In this example, elements less than 3 are replaced with 0, and others with 1.
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:NumPy on Codecademy
- Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Includes 27 Courses
- With Professional Certification
- Beginner Friendly.95 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours