numpy.select #
Return an array drawn from elements in choicelist, depending on conditions.
The list of conditions which determine from which array in choicelist the output elements are taken. When multiple conditions are satisfied, the first one encountered in condlist is used.
The list of arrays from which the output elements are taken. It has to be of the same length as condlist .
The element inserted in output when all conditions evaluate to False.
The output at position m is the m-th element of the array in choicelist where the m-th element of the corresponding array in condlist is True.
Return elements from one of two arrays depending on condition.
Beginning with an array of integers from 0 to 5 (inclusive), elements less than 3 are negated, elements greater than 3 are squared, and elements not meeting either of these conditions (exactly 3 ) are replaced with a default value of 42 .
When multiple conditions are satisfied, the first one encountered in condlist is used.
How to Use Conditional Statements with NumPy Arrays
Introduction.
NumPy is a fundamental package for scientific computing in Python. It provides an efficient way to handle large datasets by offering an array object called ndarray. Conditional statements in NumPy are powerful tools that allow you to perform element-wise operations based on certain conditions, making data analysis tasks and manipulations streamlined and fast.
In this tutorial, we’ll explore various ways to use conditional statements with NumPy arrays. From basic boolean indexing to the more advanced np.where functionality, we will cover it all with examples.
Getting Started with NumPy
First, ensure that you have NumPy installed. Install it via pip if necessary:
Once installed, you can import NumPy in your Python script or notebook:
Boolean Indexing
Boolean indexing is fundamental in NumPy, where we create a boolean array to select elements of another array that satisfy a certain condition.
This will print only the elements of arr that are greater than 3. The result is a new array containing the filtered elements.
Where Function
The np.where function is a versatile way to apply conditional logic. It takes a condition and two operands: one for when the condition evaluates to true and another for false.
In this case, the np.where function is used to create a new array where each element corresponds to ‘gt3’ if the element in arr is greater than 3, and ‘lte3’ if less than or equal to 3.
Vectored Conditional Logic
NumPy allows to express complex conditional logic using multiple nested np.where calls, acting similarly to if-else statements in traditional programming languages.
This example creates a new array with ‘lt3’, ‘eq3’, or ‘gt3’, depending on whether the respective elements in the original array are less than 3, equal to 3, or greater than 3.
Select Function
The np.select function is useful for dealing with multiple conditions. You provide a list of conditions and a list of choices to be made for each condition.
When none of the conditions is true, np.select can also take an optional default parameter to provide a default value.
Numerical Operations Based on Conditions
Conditional statements can also be used to perform numerical operations on an array based on specific criteria.
This creates a new array where every element greater than 3 is multiplied by 10, while the others remain the same.
In this tutorial, we learned how to manipulate and analyze data using conditional statements with NumPy arrays. These techniques are crucial tools in a data scientist’s toolkit, offering both simplicity and performance when handling large datasets.
Next Article: Numpy Array vs Python List: What's the Difference?
Previous Article: NumPy - Using ndarray.real attribute (4 examples)
Series: NumPy Basic Tutorials
Related Articles
- SciPy – Working with linalg.det() function (3 examples)
- SciPy linalg.solve_triangular() function (3 examples)
- SciPy linalg.solve_circulant() function (4 examples)
- SciPy – Using linalg.solveh_banded() function
- SciPy: Using linalg.solve_banded() function (3 examples)
- SciPy linalg.solve() function (4 examples)
- SciPy – Using linalg.inv() function (4 examples)
- SciPy io.arff.loadarff() function (4 examples)
- SciPy io.wavfile.read() function (4 examples)
- SciPy io.hb_write() function (4 examples)
- Using SciPy’s io.hb_read() function (3 examples)
- SciPy io.mmwrite() function (4 examples)
Search tutorials, examples, and resources
- PHP programming
- Symfony & Doctrine
- Laravel & Eloquent
- Tailwind CSS
- Sequelize.js
- Mongoose.js
Efficiently Manipulating Arrays in Python: A Case Study on Conditional Assignments
When working with arrays in Python, particularly when dealing with conditions and making assignments, it's crucial to understand the correct implementation to ensure efficient and accurate computation. In a recent discussion, a programmer encountered a challenge where two arrays, result and daysinfected , each containing 60 binary elements (0 or 1), needed to be conditionally manipulated. The objective was straightforward: set elements in result to -1 when the current element in result is greater than 0 and the corresponding element in daysinfected is 0.
The Problem
The initial attempt to solve this issue involved the following code:
However, this script did not function as expected for several reasons:
- Redundant Looping: There was an unnecessary nested loop, which could have led to inefficiencies and incorrect indexing.
- Incorrect Assignment Logic: The line i in result == -1 was meant to assign -1 to the appropriate positions in result , but instead, it just checks a condition and does not alter result . Rather, it checks if i is in result and if that boolean outcome is equal to -1 (which doesn’t make conceptual sense here).
Proposed Solution
To fix these issues, the community suggested simplifying the loop and correcting the assignment statement:
This code maintains a single loop iterating over the range of indices and correctly updates the result when the conditions are satisfied using the assignment operator = .
Optimizing with NumPy
For those working with large datasets or seeking more performant solutions, leveraging NumPy can substantially enhance both speed and readability. NumPy's where function can efficiently handle such conditions without explicit Python loops:
This method uses Boolean masking to directly apply the condition across the entire array swiftly, substituting elements in result where the condition is met.
Key Takeaways
- Single Responsibility in Loops: Ensure your loops have a single purpose and avoid unnecessary nesting unless the logic specifically requires it.
- Correct Use of Assignment Operators: Pay attention to Python's = assignment vs. comparison == to avoid logical errors.
- Utilize Libraries for Efficiency: NumPy can often replace more verbose and slower Python loops with efficient operations, particularly beneficial in data-intensive or performance-critical applications.
This particular case was an excellent example of how understanding basic programming constructs and applying the right libraries can significantly simplify and optimize your code in Python, especially when dealing with array manipulations.
numpy.where(): Manipulate elements depending on conditions
With numpy.where , you can replace or manipulate elements of the NumPy array ndarray that satisfy the conditions.
- numpy.where — NumPy v1.14 Manual
This article describes the following contents.
Overview of np.where()
Np.where() with multiple conditions, replace the elements that satisfy the condition, manipulate the elements that satisfy the condition, get the indices of the elements that satisfy the condition.
If you want to extract or delete elements, rows, and columns that satisfy the conditions, see the following article.
- NumPy: Extract or delete elements, rows, and columns that satisfy the conditions
numpy.where(condition[, x, y]) Return elements, either from x or y, depending on condition. If only condition is given, return condition.nonzero(). numpy.where — NumPy v1.14 Manual
np.where() is a function that returns ndarray which is x if condition is True and y if False . x , y and condition need to be broadcastable to same shape.
If x and y are omitted, index is returned. Details are described later.
You can get the boolean ndarray by a condition including ndarray without using np.where() .
You can apply multiple conditions with np.where() by enclosing each condition in () and using & or | .
See the following article for why you must use & , | instead of and , or and why parentheses are necessary.
- How to fix "ValueError: The truth value ... is ambiguous" in NumPy, pandas
Even in the case of multiple conditions, it is not necessary to use np.where() to get the boolean ndarray .
It is also possible to replace elements with a given value only when the condition is satisfied or not satisfied.
If you pass the original ndarray to x and y , the original value is used as it is.
Note that np.where() returns a new ndarray , and the original ndarray is unchanged.
If you want to update the original ndarray itself, you can write:
Instead of the original ndarray , you can also specify expressions for x and y .
If x and y are omitted, the indices of the elements satisfying the condition are returned.
A tuple of an array of indices (row number, column number) that satisfy the condition for each dimension (row, column) is returned.
In this case, it means that the elements at [0, 0] , [0, 1] , [0, 2] and [1, 0] satisfy the condition.
It is also possible to obtain a list of each coordinate by using list() , zip() , and * as follows:
- Transpose 2D list in Python (swap rows and columns)
The same applies to multi-dimensional arrays of three or more dimensions.
The same applies to one-dimensional arrays. Note that using list() , zip() , and * , each element in the resulting list is a tuple with one element.
If you know it is one-dimensional, you can use the first element of the result of np.where() as it is. In this case, it will be a ndarray with an integer int as an element, not a tuple with one element. If you want to convert to a list, use tolist() .
- Convert numpy.ndarray and list to each other
You can get the number of dimensions with the ndim attribute.
- NumPy: Get the number of dimensions, shape, and size of ndarray
Related Categories
Related articles.
- OpenCV, NumPy: Rotate and flip image
- NumPy: Functions ignoring NaN (np.nansum, np.nanmean, etc.)
- NumPy: Make arrays immutable (read-only) with the WRITEABLE attribute
- NumPy: Sum, mean, max, min for entire array, column/row-wise
- NumPy: Compare two arrays element-wise
- NumPy: Remove NaN (np.nan) from an array
- Method chaining across multiple lines in Python
- NumPy: Round up/down array elements (np.floor, np.trunc, np.ceil)
- NumPy: Set the display format for ndarray
- NumPy: Calculate cumulative sum and product (np.cumsum, np.cumprod)
- NumPy: Rotate array (np.rot90)
- NumPy: Count values in an array with conditions
- NumPy: Delete rows/columns from an array with np.delete()
- NumPy: Split an array with np.split, np.vsplit, np.hsplit, etc.
- NumPy: Arrange ndarray in tiles with np.tile()
COMMENTS
Return elements chosen from x or y depending on condition. When only condition is provided, this function is a shorthand for np.asarray(condition).nonzero(). Using nonzero directly should …
This tutorial teaches you how to use the where () function to select elements from your NumPy arrays based on a condition. You'll learn how to perform various operations on …
Python Conditional Assignment. When you want to assign a value to a variable based on some condition, like if the condition is true then assign a value to the variable, else assign some other …
numpy.select(condlist, choicelist, default=0) [source] #. Return an array drawn from elements in choicelist, depending on conditions. Parameters: condlistlist of bool ndarrays. The list of …
Conditional statements in NumPy are powerful tools that allow you to perform element-wise operations based on certain conditions, making data analysis tasks and …
Learn how to efficiently manipulate binary arrays in Python using conditional statements and optimize with NumPy for performance boost.
With numpy.where, you can replace or manipulate elements of the NumPy array ndarray that satisfy the conditions. numpy.where — NumPy v1.14 Manual; This article describes the following contents. Overview of np.where() …