Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Numpy exercise
  • pandas
  • Matplotlib
  • Data visulisation
  • EDA
  • Machin Learning
  • Deep Learning
  • NLP
  • Data science
  • ML Tutorial
  • Computer Vision
  • ML project
Open In App
Next Article:
numpy.who function - Python
Next article icon

numpy.select() function – Python

Last Updated : 07 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

Python
import numpy as np arr = np.array([10, 20, 30, 40]) conditions = [arr < 20, arr > 30] choices = [100, 200] result = np.select(conditions, choices, default=0) print(result) 

Syntax:

numpy.select(condlist, choicelist, default=0)

Parameters:

  • condlist : list of bool ndarrays
    A list of boolean NumPy arrays that determine from which array in choicelist the output elements are selected. If multiple conditions are True, the first one encountered is used.
  • choicelist : list of ndarrays
    A list of arrays from which the output elements are chosen. It must have the same length as condlist.
  • default : scalar, optional (default=0)
    The value inserted in the output array when none of the conditions are met.

Return Value:

  • ndarray : An array with elements chosen from choicelist based on the conditions in condlist.

Code Implementation

1. Basic Usage of numpy.select()

Here:

  • If arr < 3, the corresponding element is taken from arr.
  • If arr > 4, the corresponding element is taken from arr**3.
  • Otherwise, the default value 0 is used.
Python
import numpy as np arr = np.arange(8) condlist = [arr < 3, arr > 4] choicelist = [arr, arr**3] result = np.select(condlist, choicelist) print(result) 

Output :

[ 0 1 2 0 0 125 216 343]

2. Using a Different Default Value

Here:

  • Values where arr < 4 are taken from arr.
  • Values where arr > 6 are taken from arr**2.
  • All other values are replaced with -1 (instead of 0).
Python
arr = np.arange(8) condlist = [arr < 4, arr > 6] choicelist = [arr, arr**2]  # Custom default value (e.g., -1) result = np.select(condlist, choicelist, default=-1) print(result) 

Output:

0 1 2 3 -1 -1 -1 49]

3. Handling Multiple Conditions

Here :

  • If arr is even (arr % 2 == 0), it is multiplied by 10.
  • If arr is divisible by 3 (arr % 3 == 0), it is negated.
  • If neither condition is met, the default value 100 is used.
Python
arr = np.arange(10) condlist = [arr % 2 == 0, arr % 3 == 0] choicelist = [arr * 10, arr * -1]  result = np.select(condlist, choicelist, default=100) print(result) 

Output:

[ 0 100 20 -3 40 100 60 100 80 -9]

Why Use numpy.select()?

  • More flexible than numpy.where() when dealing with multiple conditions.
  • Helps avoid complex nested if-else conditions in array transformations.
  • Efficient and concise for applying different transformations to an array based on conditions.

Comparison with numpy.where()

Featurenumpy.select()numpy.where()
Multiple ConditionsYesNo (only two conditions: True/False)
Custom Default ValueYesNo
SimplicityBetter for multiple rulesBetter for simple if-else

The numpy.select() function is a powerful tool for conditional selection and transformation of array elements. It is especially useful when handling multiple conditions efficiently in a structured way. Mastering its usage will help simplify complex array operations in Python.



Next Article
numpy.who function - Python
author
sanjoy_62
Improve
Article Tags :
  • Machine Learning
  • Numpy
  • python
  • Python numpy-arrayManipulation
  • Python-numpy
Practice Tags :
  • Machine Learning
  • python

Similar Reads

  • Numpy size() function | Python
    numpy.size() function in Python is used to count the number of elements in a NumPy array. You can use it to get the total count of all elements, or to count elements along a specific axis, such as rows or columns in a multidimensional array. This makes it useful when quickly trying to understand the
    2 min read
  • numpy.roots() function - Python
    numpy.roots() function return the roots of a polynomial with coefficients given in p. The values in the rank-1 array p are coefficients of a polynomial. If the length of p is n+1 then the polynomial is described by: p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n] Syntax : numpy.roots(p) Parame
    1 min read
  • 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
  • numpy.sctype2char() function – Python
    numpy.sctype2char() function return the string representation of a scalar dtype. Syntax : numpy.sctype2char(sctype) Parameters : sctype : [scalar dtype or object] If a sctype is a scalar dtype, the corresponding string character is returned. If an object, sctype2char tries to infer its scalar type a
    1 min read
  • numpy.i0() function | Python
    numpy.i0() function is the modified Bessel function of the first kind, order 0. it's usually denoted by I0. Syntax : numpy.i0(x) Parameters : x : [array_like, dtype float or complex] Argument of the Bessel function. Return : [ndarray, shape = x.shape, dtype = x.dtype] The modified Bessel function ev
    1 min read
  • Numpy recarray.any() function | Python
    In numpy, arrays may have a data-types containing fields, analogous to columns in a spreadsheet. An example is [(a, int), (b, float)], where each entry in the array is a pair of (int, float). Normally, these attributes are accessed using dictionary lookups such as arr['a'] and arr['b']. Record array
    3 min read
  • vars() function in Python
    vars() method takes only one parameter and that too is optional. It takes an object as a parameter which may be a module, a class, an instance, or access the __dict__ attribute in Python. In this article, we will learn more about vars() function in Python. Python vars() Function Syntax Syntax: vars(
    3 min read
  • numpy.where() in Python
    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 fro
    3 min read
  • numpy.fromiter() function – Python
    NumPy's fromiter() function is a handy tool for creating a NumPy array from an iterable object. This iterable can be any Python object that provides elements one at a time. The function is especially useful when you need to convert data from a custom data source, like a file or generator, into a Num
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences