• Post author:
  • Post category:NumPy / Python
  • Post last modified:March 27, 2024
  • Reading time:17 mins read
You are currently viewing NumPy Count Nonzero Values in Python

NumPy count_nonzero() function in Python is used to count the number of nonzero elements present in the one-dimensional or multi-dimensional array. This function has 3 parameters as arr, axis, and keepdims. In this article, I will explain the syntax of NumPy count_nonzero() and use this function to count the number of nonzero values in the input array.

Advertisements

1. Quick Examples of NumPy Count Nonzero Values

If you are in a hurry, below are some quick examples of how to get the count of nonzero by using NumPy count_nonzero() function in Python. For more examples of NumPy refer to NumPy Tutorial.


# Quick examples of numpy count nonzero values

# Example 1:Count non-zero elements in numpy array
arr = np.array([8, 23, 45, 0, 60, 0, 85, 0, 101])
arr2 = np.count_nonzero(arr)

# Example 2: Count values in numpy array 
# That satisfy a condition 
arr2 = np.count_nonzero(arr % 45 == 0)

# Example 3: Count the number of elements 
# That satisfy the condition
arr2 = np.count_nonzero(arr > 8)

# Example 4: Get numpy count_nonzero() value of 2-d array
arr = np.array([[4, 0, 0, 12], [15, 0, 26, 34], [0, -7, 15, 0]])
arr2 = np.count_nonzero(arr)

# Example 5: Count nonzero elements along axis 0 (columns)   
arr2 = np.count_nonzero(arr, axis = 0)

# Example 6: Count nonzero elements along axis 1 (rows)
arr2 = np.count_nonzero(arr, axis = 1)  
  
# Example 7: Count nonzero elements along axis 1 (rows) 
# With keepdims=True
arr2 = np.count_nonzero(arr, axis=1, keepdims=True)

# Example 8: Get counting true elements in numpy array
arr = np.array([True, True, False, True, False, True, False, True, False])
arr2 = np.count_nonzero(arr)

2. Syntax of NumPy count_nonzero()

Following is the syntax of the numpy.count_nonzero() function.


# Syntax of numpy.count_nonzero()
numpy.count_nonzero(arr, axis=None, *, keepdims=False)

2.1 Parameters of count_nonzero()

The count_nonzero() function allows the following parameters.

  • arr - This is the input array for which you want to count non-zero elements.
  • axis - Axis or tuple of axes along which to count nonzeros. By default, a flattened array is used. axis = 0 means along the column and axis = 1 means working along the row.
  • keepdims - The value is set to be True, this creates reduced axes with dimensions of one size.

2.2 Return Value of count_nonzero()

It returns int or array of int with number of nonzero values in the array along a given axis. If no axis specified, the total number of nonzero values in the array is returned.

3. Count nonzero Elements in NumPy Array

Let’s count the number of nonzero values of a single-dimension array using the NumPy count_nonzero() function. This function takes the array as input and returns the count of the elements by ignoring zeros.

You can use np.count_nonzero() to get the count of non-zero elements in a 1D NumPy array. The value of arr2 in your code is the count of non-zero elements, so you don’t need to change anything.


# Import numpy
import numpy as np

# Create one-dimensional array of numbers
arr = np.array([8, 23, 45, 0, 60, 0, 85, 0, 101])
print("Original array:",arr) 

# Count non-zero elements in numpy array
arr2 = np.count_nonzero(arr)
print("Number of non-zero elements:",arr2) 

Yields below output.

numpy count nonzero

4. Count Values in Numpy Array that Satisfy a Condition

To count the values in a NumPy array that satisfy a specific condition, you can use boolean indexing and then apply the numpy.count_nonzero() function.

In the below example, the condition is defined as arr > 8, which creates a boolean array of the same shape as arr with True where the condition is satisfied and False where it is not. You can modify the condition according to your requirements. The np.count_nonzero() function is then used to count the number of True values in the boolean array, which corresponds to the number of elements in the original array that satisfy the condition.


# Count the number of elements 
# That satisfy the condition
arr2 = np.count_nonzero(arr > 8)
print("Number of elements satisfying the condition:",arr2)

# Output:
# Number of elements satisfying the condition: 5

# Count values in numpy array 
# That satisfy a condition 
arr2 = np.count_nonzero(arr % 45 == 0)
print("Number of elements satisfying the condition:",arr2) 

# Output:
# Number of elements satisfying the condition: 4 

5. Get NumPy count_nonzero() Value of 2-D Array

To get the count of nonzero values in a 2D NumPy array using np.count_nonzero(), you can apply the function directly to the array. If you don’t specify the axis, it just flattens the array and returns the count by ignoring zero values.

In the below example, arr is a 3×4 2D NumPy array. The np.count_nonzero() function is applied directly to arr to count the number of nonzero elements in the entire 2D array.


import numpy as np

# Create 2-D array
arr = np.array([[4, 0, 0, 12], [15, 0, 26, 34], [0, -7, 15, 0]])
print("Original array:\n",arr)

# Count nonzero elements in the 2D array
arr2 = np.count_nonzero(arr)
print("Number of nonzero elements in the 2D array:",arr2)

# Output:
# Original array:
#  [[ 4  0  0 12]
#  [15  0 26 34]
#  [ 0 -7 15  0]]
# Number of nonzero elements in the 2D array: 7

6. Get NumPy count_nonzero() along the Axis

To use np.count_nonzero() along a specific axis in a NumPy array, you can specify the axis parameter. This will give you the count of nonzero elements along the specified axis.

In the below example, np.count_nonzero(arr, axis=0) counts the number of nonzero elements along each column (axis 0) of the 2D array arr. You can also use axis=1 to count nonzero elements along rows.


# Count nonzero elements along axis 0 (columns) 
arr2 = np.count_nonzero(arr, axis = 0)
print("Number of nonzero elements along axis 0 (columns):\n", arr2)

# Output:
# Number of nonzero elements along axis 0 (columns):
#  [2 1 2 2]

# Count nonzero elements along axis 1 (rows)
arr2 = np.count_nonzero(arr, axis = 1)
print("Number of nonzero elements along axis 1 (rows):\n", arr2) 

# Output:
# Number of nonzero elements along axis 1 (rows):
#  [2 3 2]

7. Use axis=1 and keepdims = True

You can also use NumPy to count the nonzero value of an array along with the axis=1 and keepdims=True, the keepdims argument keeps the dimensions in the result.

In the below example, np.count_nonzero(arr, axis=1, keepdims=True) counts the number of nonzero elements along each row (axis 1) of the 2D array arr while keeping the dimensionality of the result consistent with the original array.


# Count nonzero elements along axis 1 (rows) with keepdims=True
arr2 = np.count_nonzero(arr, axis=1, keepdims=True)
print("Number of nonzero elements along axis 1 with keepdims=True:", arr2)

# Output:
# Number of nonzero elements along axis 1 with keepdims=True
# [[2]
#  [3]
#  [2]]

8. Get Counting True Elements in NumPy Array

You can use numpy.count_nonzero() function to count the True elements in a bool numpy array. Python True is equivalent to one and False is equivalent to zero.


import numpy as np

# Create array
arr = np.array([True, True, False, True, False, True, False, True, False])

# Get counting true elements in numpy array
arr2 = np.count_nonzero(arr)
print("Number of True elements:",arr2) 

# Output:
# Number of True elements: 5

Frequently Asked Questions

How do I count nonzero elements in a 1D NumPy array?

To count nonzero elements in a 1D NumPy array, you can use the np.count_nonzero() function. For example, arr is a 1D NumPy array, and np.count_nonzero() is used to count the number of nonzero elements in the array

How can I count nonzero elements in a 2D NumPy array?

To count nonzero elements in a 2D NumPy array, you can use the np.count_nonzero() function. For example, arr is a 2D NumPy array, and np.count_nonzero() is used to count the number of nonzero elements in the entire 2D array. If you want to count nonzero elements along a specific axis (e.g., along columns or rows), you can use the axis parameter.

Can I count nonzero elements along a specific axis in a 2D array?

You can count nonzero elements along a specific axis in a 2D NumPy array using the np.count_nonzero() function with the axis parameter.

How do I count True elements in a boolean array?

To count True elements in a boolean array, you can use the np.sum() function. For example, arr is a boolean array. The np.sum(arr) counts the number of True elements in the boolean array. The result is the total count of True values in the array.

What if I want to keep the dimensions when counting along an axis?

If you want to keep the dimensions when counting along an axis in a NumPy array, you can use the np.sum() function with the axis and keepdims parameters.

Conclusion

In this article, I have explained how to use NumPy count_nonzero() function in Python and using this function how to get count the number of nonzero values for 1-dimension and 2-dimension arrays along with specified axes.

Happy Learning!!

References