We will explore the basics of numpy.where(), how it works, and practical use cases to illustrate its importance in data manipulation and analysis.
Syntax of numpy.where()
Syntax :numpy.where(condition[, x, y])
Parameters
- condition: A condition that tests elements of the array.
- x (optional): Values from this array will be returned where the condition is True.
- y (optional): Values from this array will be returned where the condition is False.
Returns: If only the condition is provided, numpy.where() will return the indices of elements where the condition is true.
Uses of Numpy Where
The numpy.where() function is a powerful tool in the NumPy library used for conditional selection and manipulation of arrays. This function enables you to search, filter, and apply conditions to elements of an array, returning specific elements based on the condition provided.
Basic Usage Without x
and y
If only the condition is provided, numpy.where()
returns the indices of elements that meet the condition.
In this example, numpy.where()
checks where the condition arr > 20
is true, and returns the indices [3, 4]
, meaning the elements at index 3 and 4 (25 and 30) are greater than 20.
Python
import numpy as np
# Create an array
arr = np.array([10, 15, 20, 25, 30])
# Use np.where() to find indices of elements greater than 20
result = np.where(arr > 20)
print(result)
Output:
(array([3, 4]),)
Using numpy.where()
with x
and y
By providing x
and y
as arguments, you can use numpy.where()
to return different values depending on whether the condition is true or false.
Here, the numpy.where()
function checks the condition arr > 20
. For elements that meet the condition, it returns 1
, and for those that don't, it returns 0
. This is a common technique to apply binary masks in arrays.
Python
import numpy as np
# Create an array
arr = np.array([10, 15, 20, 25, 30])
# Use np.where() to replace values based on condition
# If the value is greater than 20, return 1, otherwise return 0
result = np.where(arr > 20, 1, 0)
print(result)
Output:
[0 0 0 1 1]
Conditional Selection of Elements from Two Arrays
You can also use numpy.where()
to choose elements from two different arrays depending on a condition.
In this example, for elements where the condition arr1 > 20
is true, the corresponding element from arr1
is chosen. Otherwise, the element from arr2
is selected.
Python
import numpy as np
# Create two arrays
arr1 = np.array([10, 15, 20, 25, 30])
arr2 = np.array([100, 150, 200, 250, 300])
# Use np.where() to select elements from arr1 where the condition is true, and arr2 otherwise
result = np.where(arr1 > 20, arr1, arr2)
print(result)
Output:
[100 150 200 25 30]
Similar Reads
numpy.ma.where() function - Python numpy.ma.where() function return a masked array with elements from x or y, depending on condition. Syntax : numpy.ma.where(condition, x, y) Parameter : condition : [array_like, bool] Where True, yield x, otherwise yield y. x, y : [array_like, optional] Values from which to choose. x, y and condition
1 min read
numpy.who function - Python numpy.who() function print the NumPy arrays in the given dictionary. Syntax : numpy.who(vardict = None) Parameters : vardict : [dict, optional] A dictionary possibly containing ndarrays. Return : Returns âNoneâ. If there is no dictionary passed in or vardict is None then returns NumPy arrays in the
1 min read
Python | Pandas Index.where Pandas Index is an immutable ndarray implementing an ordered, sliceable set. It is the basic object which stores the axis labels for all pandas objects. Pandas Index.where function return an Index of same shape as self and whose corresponding entries are from self where cond is True and otherwise ar
2 min read
numpy.select() function - Python The numpy.select() function is used to construct an array by selecting elements from a list of choices based on multiple conditions. It is particularly useful when dealing with conditional replacements or transformations in NumPy arrays. Example:Pythonimport numpy as np arr = np.array([10, 20, 30, 4
3 min read
numpy.find() in Python numpy.core.defchararray.find(arr, substring, start=0, end=None): Finds the lowest index of the sub-string in the specified range. Parameters: arr : array-like or string to be searched. substring : substring to search for. start, end : [int, optional] Range to search in. Returns : An integer array wi
1 min read
numpy.index() in Python numpy.core.defchararray.index(arr, substring, start=0, end=None): Finds the lowest index of the sub-string in the specified range But if substring is not found, it raises ValueError. Parameters: arr : array-like or string to be searched. substring : substring to search for. start, end : [int, option
1 min read
Python MySQL - Where Clause Where clause is used in MySQL database to filter the data as per the condition required. You can fetch, delete or update a particular set of data in MySQL database by using where clause.Syntax SELECT column1, column2, .... columnN FROM [TABLE NAME] WHERE [CONDITION];  The above syntax is used for
2 min read
re.findall() in Python re.findall() method in Python helps us find all pattern occurrences in a string. It's like searching through a sentence to find every word that matches a specific rule. We can do this using regular expressions (regex) to create the pattern and then use re.findall() to get a list of matches.Let's say
2 min read
numpy.argwhere() in Python numpy.argwhere() function is used to find the indices of array elements that are non-zero, grouped by element. Syntax : numpy.argwhere(arr) Parameters : arr : [array_like] Input array. Return : [ndarray] Indices of elements that are non-zero. Indices are grouped by element. Code #1 : Python3 # Pytho
1 min read
Numpy MaskedArray.masked_where() function | Python In many circumstances, datasets can be incomplete or tainted by the presence of invalid data. For example, a sensor may have failed to record a data, or recorded an invalid value. The numpy.ma module provides a convenient way to address this issue, by introducing masked arrays.Masked arrays are arra
3 min read