0
0
NumPydata~5 mins

np.choose() for conditional selection in NumPy

Choose your learning style9 modes available
Introduction

We use np.choose() to pick values from multiple options based on conditions. It helps select data easily without writing many if-else statements.

You want to assign categories to numbers based on ranges.
You need to select different arrays depending on a condition array.
You want to replace values in an array based on multiple conditions.
You want a simple way to map indices to values in data analysis.
Syntax
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.

Examples
This picks values from three arrays based on index. For example, index 0 picks from choices, index 1 picks from choices*2, etc.
NumPy
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)
Here, cond selects which array value to pick for each position.
NumPy
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)
Sample Program

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.

NumPy
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)
OutputSuccess
Important Notes

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().

Summary

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.