How to check if all the values in a numpy array are non-zero?

NumpyPythonServer Side ProgrammingProgramming

In this program, we have to check whether all the values in a numpy array are zero or not. If all the elements are non-zero, the output is 'True'. Otherwise, the output is 'False'.

The most important Step before implementing the algorithm for this program is to install numpy. Following is the command for installing numpy from command prompt:

pip install numpy

Example

Input:

[1,2,3,4]

Output:

True

Input:

[0,1,2,3]

Output:

False

Explanation

We shall use the numpy built-in function called 'all(input_array)'. This function checks every number in the array. If the number is non-zero, the function returns 'True'. All non-zero elements are evaluated as 'True', while 0's are evaluated as 'False'.

Algorithm

Step 1: Import numpy.

Step 2: Define a numpy array using np.array()

Step 3: Pass this array as a parameter to np.all()

Step 4: Stop.

Example Code

import numpy as np

array1 = np.array([1,2,3,4])
array2 = np.array([0,1,2,3])

print("Array 1: ", array1)
print("Array2: ", array2)
print("\nArray 1 is non-zero: ", np.all(array1))
print("Array 2 is non-zero: ", np.all(array2))

Output

Array 1: [1 2 3 4]
raja
Published on 16-Mar-2021 09:37:15
Advertisements