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
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
numpy.array_equal() in Python
Next article icon

Boolean Array in NumPy - Python

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

The goal here is to work with Boolean arrays in NumPy, which contain only True or False values. Boolean arrays are commonly used for conditional operations, masking and filtering elements based on specific criteria. For example, given a NumPy array [1, 0, 1, 0, 1], we can create a Boolean array where 1 becomes True and 0 becomes False. Let's explore different efficient methods to achieve this.

Using astype()

astype() method is an efficient way to convert an array to a specific data type. When converting an integer array to a Boolean array, astype(bool) converts all non-zero values to True and zeros to False. This method is preferred for its directness and speed.

Python
import numpy as np a = np.array([1, 0, 1, 0, 0, 1, 0])  b = a.astype(bool) print(b) 

Output
[ True False  True False False  True False] 

Explanation: astype(bool) method converts non-zero values to True and zeros to False. So, the array [1, 0, 1, 0, 0, 1, 0] becomes [True, False, True, False, False, True, False].

Using dtype='bool'

When creating a NumPy array, you can specify the dtype='bool' argument to directly convert the data type to Boolean. This method is efficient because it processes the conversion during the array creation step, providing a clean and fast approach to generating a Boolean array from integers.

Python
import numpy as np a = np.array([1, 0, 1, 0, 0, 1, 0])  b = np.array(a, dtype=bool) print(b) 

Output
[ True False  True False False  True False] 

Explanation: dtype=bool argument convert the array a into Boolean values. It treats non-zero values as True and zeros as False.

Using np.where()

np.where() function in NumPy is a versatile tool for conditional operations. It checks each element against a condition (e.g., arr == 1) and returns True or False. While less efficient than direct type conversion, it allows for custom conditions and complex logic.

Python
import numpy as np a = np.array([1, 0, 1, 0, 0, 1, 0])  b = np.where(a == 1, True, False) print(b) 

Output
[ True False  True False False  True False] 

Explanation: np.where() function checks each element of the array a against the condition a == 1. If the condition is true (i.e., the element is 1), it returns True otherwise, it returns False.

Using a comparison with == 1

Using == 1 creates a Boolean array by checking if elements are equal to 1, returning True for 1 and False otherwise. While simple and efficient, it's slightly less efficient than astype() or dtype='bool' due to the explicit element check.

Python
import numpy as np a = np.array([1, 0, 1, 0, 0, 1, 0])  b = a == 1 print(b) 

Output
[ True False  True False False  True False] 

Explanation: a == 1 checks each element of the array a to see if it is equal to 1. It returns a Boolean array where True corresponds to elements that are 1 and False for all other values.



Next Article
numpy.array_equal() in Python
author
akashjha2671
Improve
Article Tags :
  • Technical Scripter
  • Python
  • Technical Scripter 2022
Practice Tags :
  • python

Similar Reads

  • numpy.array_equal() in Python
    numpy.array_equal(arr1, arr2) : This logical function that checks if two arrays have the same shape and elements. Parameters : arr1 : [array_like]Input array or object whose elements, we need to test. arr2 : [array_like]Input array or object whose elements, we need to test. Return : True, if both ar
    1 min read
  • NumPy Array in Python
    NumPy (Numerical Python) is a powerful library for numerical computations in Python. It is commonly referred to multidimensional container that holds the same data type. It is the core data structure of the NumPy library and is optimized for numerical and scientific computation in Python. Table of C
    2 min read
  • numpy.asarray() in Python
    numpy.asarray()function is used when we want to convert input to an array. Input can be lists, lists of tuples, tuples, tuples of tuples, tuples of lists and arrays. Syntax : numpy.asarray(arr, dtype=None, order=None) Parameters : arr : [array_like] Input data, in any form that can be converted to a
    2 min read
  • Python - Numpy Array Column Deletion
    Given a numpy array, write a programme to delete columns from numpy array. Examples - Input: [['akshat', 'nikhil'], ['manjeeet', 'akash']] Output: [['akshat']['manjeeet']] Input: [[1, 0, 0, 1, 0], [0, 1, 2, 1, 1]] Output: [[1 0 1 0][0 2 1 1]] Given below are various methods to delete columns from nu
    2 min read
  • numpy.asfarray() in Python
    numpy.asfarray()function is used when we want to convert input to a float type array. Input includes scalar, lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays. Syntax : numpy.asfarray(arr, dtype=type 'numpy.float64') Parameters : arr : [array_like] Input data, in any for
    2 min read
  • numpy.array_str() in Python
    numpy.array_str()function is used to represent the data of an array as a string. The data in the array is returned as a single string. This function is similar to array_repr, the difference being that array_repr also returns information on the kind of array and its data type. Syntax : numpy.array_st
    2 min read
  • Python | Numpy numpy.ndarray.__ne__()
    With the help of numpy.ndarray.__ne__() method of Numpy, We can find that which element in an array is not equal to the value which is provided in the parameter. It will return you numpy array with boolean type having only values True and False. Syntax: ndarray.__ne__($self, value, /) Return: self!=
    1 min read
  • numpy.asanyarray() in Python
    numpy.asanyarray()function is used when we want to convert input to an array but it pass ndarray subclasses through. Input can be scalars, lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays. Syntax : numpy.asanyarray(arr, dtype=None, order=None) Parameters : arr : [array_
    2 min read
  • numpy.array_repr() in Python
    numpy.array_repr()function is used to convert an array to a string. Syntax : numpy.array_repr(arr, max_line_width=None, precision=None, suppress_small=None) Parameters : arr : [array_like] Input array. max_line_width : [int, optional] The maximum number of columns the string should span. Newline cha
    2 min read
  • numpy.any() in Python
    The numpy.any() function tests whether any array elements along the mentioned axis evaluate to True. Syntax : numpy.any(a, axis = None, out = None, keepdims = class numpy._globals._NoValue at 0x40ba726c) Parameters : array :[array_like]Input array or object whose elements, we need to test. axis : [i
    3 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