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:
Counting the number of non-NaN elements in a NumPy Array
Next article icon

Find indices of elements equal to zero in a NumPy array

Last Updated : 08 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes we need to find out the indices of all null elements in the array. Numpy provides many functions to compute indices of all null elements. 

Method 1: Finding indices of null elements using numpy.where()

This function returns the indices of elements in an input array where the given condition is satisfied.

Syntax : 

numpy.where(condition[, x, y]) When True, yield x, otherwise yield y

Python3

# importing Numpy package
import numpy as np
 
# creating a 1-D Numpy array
n_array = np.array([1, 0, 2, 0, 3, 0, 0, 5,
                    6, 7, 5, 0, 8])
 
print("Original array:")
print(n_array)
 
# finding indices of null elements using np.where()
print("\nIndices of elements equal to zero of the \
given 1-D array:")
 
res = np.where(n_array == 0)[0]
print(res)
                      
                       

Output:

Time complexity: O(n) – where n is the size of the array
Auxiliary space: O(k) – where k is the number of null elements in the array, as we are storing their indices in a separate array.

Method 2: Finding indices of null elements using numpy.argwhere()

This function is used to find the indices of array elements that are non-zero, grouped by element.

Syntax : 

numpy.argwhere(arr)

Python3

# importing Numpy package
import numpy as np
 
# creating a 3-D Numpy array
n_array = np.array([[0, 2, 3],
                    [4, 1, 0],
                    [0, 0, 2]])
 
print("Original array:")
print(n_array)
 
# finding indices of null elements
# using np.argwhere()
print("\nIndices of null elements:")
res = np.argwhere(n_array == 0)
 
print(res)
                      
                       

Output:

The time complexity of the code is O(m * n) where m and n are the dimensions of the 3-D Numpy array .

The auxiliary space complexity of the code is O(k) where k is the number of null elements in the 3-D Numpy array .

Method 3: Finding the indices of null elements using numpy.nonzero()

This function is used to Compute the indices of the elements that are non-zero. It returns a tuple of arrays, one for each dimension of arr, containing the indices of the non-zero elements in that dimension.

Syntax:

numpy.nonzero(arr)

Python3

# importing Numpy package
import numpy as np
 
# creating a 1-D Numpy array
n_array = np.array([1, 10, 2, 0, 3, 9, 0,
                    5, 0, 7, 5, 0, 0])
 
print("Original array:")
print(n_array)
 
# finding indices of null elements using
# np.nonzero()
print("\nIndices of null elements:")
 
res = np.nonzero(n_array == 0)
print(res)
                      
                       

Output:

The time complexity  is O(n), where n is the number of elements in the input array. 

The auxiliary space complexity  is O(k), where k is the number of null elements in the input array. 

Method 4: Using numpy.extract() method

Use the numpy.extract() method. This method returns an array of values that satisfy a certain condition. In this case, we can use it to extract the indices of elements that are equal to zero.

Python3

# importing Numpy package
import numpy as np
 
# creating a 1-D Numpy array
n_array = np.array([1, 0, 2, 0, 3, 0, 0, 5,
                    6, 7, 5, 0, 8])
 
print("Original array:")
print(n_array)
 
# finding indices of null elements using np.extract()
print("\nIndices of elements equal to zero of the \
given 1-D array:")
 
res = np.extract(n_array == 0, np.arange(len(n_array)))
print(res)
                      
                       

Output:

Original array: [1 0 2 0 3 0 0 5 6 7 5 0 8] Indices of elements equal to zero of the given 1-D array: [ 1  3  5  6 11]

Time complexity: O(n), where n is the length of the input array.
Auxiliary space: O(m), where m is the number of elements in the input array that are equal to zero. 



Next Article
Counting the number of non-NaN elements in a NumPy Array
author
vanshgaur14866
Improve
Article Tags :
  • Python
  • Python numpy-Indexing
  • Python-numpy
Practice Tags :
  • python

Similar Reads

  • Test whether the elements of a given NumPy array is zero or not in Python
    In numpy, we can check that whether none of the elements of given array is zero or not with the help of numpy.all() function. In this function pass an array as parameter. If any of one element of the passed array is zero then it returns False otherwise it returns True boolean value. Syntax: numpy.al
    2 min read
  • How to check whether the elements of a given NumPy array is non-zero?
    In NumPy with the help of any() function, we can check whether any of the elements of a given array in NumPy is non-zero. We will pass an array in the any() function if it returns true then any of the element of the array is non zero if it returns false then all the elements of the array are zero. S
    1 min read
  • Counting the number of non-NaN elements in a NumPy Array
    In this article, we are going to see how to count the number of non-NaN elements in a NumPy array in Python. NAN: It is used when you don't care what the value is at that position. Maybe sometimes is used in place of missing data, or corrupted data.  Method 1: Using Condition In this example, we wil
    3 min read
  • Find the sum and product of a NumPy array elements
    In this article, let's discuss how to find the sum and product of NumPy arrays.  Sum of the NumPy array Sum of NumPy array elements can be achieved in the following ways Method #1:  Using numpy.sum() Syntax: numpy.sum(array_name, axis=None, dtype=None, out=None, keepdims=<no value>, initial=
    5 min read
  • How to find the Index of value in Numpy Array ?
    In this article, we are going to find the index of the elements present in a Numpy array. Using where() Methodwhere() method is used to specify the index of a particular element specified in the condition. Syntax: numpy.where(condition[, x, y]) Example 1: Get index positions of a given valueHere, we
    5 min read
  • NumPy| How to get the unique elements of an Array
    To find unique elements of an array we use the numpy.unique() method of the NumPy library in Python. It returns unique elements in a new sorted array. Example: [GFGTABS] Python3 import numpy as np arr = np.array([1, 2, 3, 1, 4, 5, 2, 5]) unique_elements = np.unique(arr) print(unique_elements) [/GFGT
    2 min read
  • NumPy ndarray.__abs__() | Find Absolute Value of Elements in NumPy Array
    The ndarray.__abs__() method returns the absolute value of every element in the NumPy array. It is automatically invoked when we use Python's built-in method abs() on a NumPy array. Example C/C++ Code import numpy as np gfg = np.array([1.45, 2.32, 3.98, 4.41, 5.55, 6.12]) print(gfg.__abs__()) Output
    1 min read
  • Find the length of each string element in the Numpy array
    NumPy builds on (and is a successor to) the successful Numeric array object. Its goal is to create the corner-stone for a useful environment for scientific computing. NumPy provides two fundamental objects: an N-dimensional array object (ndarray) and a universal function object (ufunc). In this post
    3 min read
  • NumPy ndarray.size() Method | Get Number of Elements in NumPy Array
    The ndarray.size() method returns the number of elements in the NumPy array. It works the same as np.prod(a.shape), i.e., the product of the dimensions of the array. Example C/C++ Code import numpy as np arr = np.zeros((3, 4, 2), dtype = np.complex128) gfg = arr.size print (gfg) Output : 24Syntax Sy
    1 min read
  • NumPy indices() Method | Create Array of Indices
    The indices() method returns an array representing the indices of a grid. It computes an array where the subarrays contain index values 0, 1, … varying only along the corresponding axis. Example C/C++ Code import numpy as np gfg = np.indices((2, 3)) print (gfg) Output : [[[0 0 0] [1 1 1]] [[0 1 2] [
    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