How to check whether the elements of a given NumPy array is non-zero?

How to check whether the elements of a given NumPy array is non-zero?

In NumPy, you can use the np.nonzero() function to check for non-zero elements in an array. This function returns the indices of the non-zero elements.

Here's an example of how to use it:

import numpy as np # Create a numpy array array = np.array([1, 0, 2, 0, 3, 0, 4]) # Get the indices of non-zero elements non_zero_indices = np.nonzero(array) print("Indices of non-zero elements:", non_zero_indices) print("Non-zero elements:", array[non_zero_indices]) 

If you want to create a boolean array indicating whether each element is non-zero, you can use the following:

# Create a boolean array where True indicates non-zero non_zero_bool_array = array != 0 print("Boolean array where True indicates non-zero:", non_zero_bool_array) 

This boolean array can then be used to perform boolean indexing or other operations that rely on the position of non-zero elements.


More Tags

swrevealviewcontroller sorting jsonconvert copy composite-key algorithms amazon-athena derivative gradlew build-tools

More Programming Guides

Other Guides

More Programming Examples