We use np.choose() to pick values from multiple options based on conditions. It helps select data easily without writing many if-else statements.
np.choose() for conditional selection in NumPy
np.choose(index_array, [option1, option2, option3, ...])
index_array contains integers that act as indices to pick from the options list.
All options must have the same shape or be broadcastable to the same shape.
index. For example, index 0 picks from choices, index 1 picks from choices*2, etc.import numpy as np choices = np.array([10, 20, 30]) index = np.array([0, 1, 2]) result = np.choose(index, [choices, choices*2, choices*3]) print(result)
cond selects which array value to pick for each position.import numpy as np cond = np.array([1, 0, 2, 1]) options = [np.array([100, 100, 100, 100]), np.array([200, 200, 200, 200]), np.array([300, 300, 300, 300])] result = np.choose(cond, options) print(result)
This program assigns grades to scores using np.choose(). We first create an index array where each score is mapped to 0, 1, or 2 based on its value. Then, np.choose() picks the grade label for each score.
import numpy as np # Suppose we have scores and want to assign grades: # 0 = Fail, 1 = Pass, 2 = Excellent scores = np.array([55, 70, 85, 40, 95]) # Create an index array based on score ranges index = np.where(scores < 60, 0, np.where(scores < 80, 1, 2)) # Define grade labels grades = np.array(['Fail', 'Pass', 'Excellent']) # Use np.choose to pick grade labels result = np.choose(index, [grades[0], grades[1], grades[2]]) print(result)
The index_array must contain integers starting from 0 up to the number of options minus one.
If the shapes of options differ, NumPy tries to broadcast them to a common shape.
Use np.where() to create the index array for complex conditions before using np.choose().
np.choose() selects elements from multiple arrays based on an index array.
It simplifies conditional selection without many if-else statements.
Make sure the index array and options have compatible shapes.