Author -  Sai gowtham

How to check if a NumPy array has all zeros in Python

In this tutorial, we are going to learn about how to check if a NumPy array has all zeros in Python with the help of examples.

In Python NumPy is used to work with arrays. The array object in NumPy is called ndarray.

Consider, that we are having the following NumPy array contains only zeros in it.

import numpy as np

prices = np.array([0, 0, 0, 0])

Using any() function

To check if an NumPy array contains all zeros, we can use the any() function in Python.

The any() function accepts the NumPy array as an argument and checks whether any of the elements in array evaluates to the boolean value True or not. If any of the element is evaluates to true then it returns true. If all the elements contains zero values it evaluates to False.

Here is an example:

import numpy as np

prices = np.array([0, 0, 0, 0])

if not np.any(prices):
    print('Array contains all zeros')
else:
    print('Array contains non zero values')

Output:

Array contains all zeros

Using the numpy.count_nonzero()

The numpy.count_nonzero() function takes the numpy array as argument and returns the number of non zero values in the array. By using that we can check if a array contains all zeros or not.

Here is an example:

import numpy as np

prices = np.array([0, 0, 0, 0])

if  np.count_nonzero(prices) == 0:
    print('Array contains all zeros')
else:
    print('Array contains non zero values')

Additional resources

You can also check following tutorials in Python:

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY