Count the occurrence of a certain item in an array using sum()
A True is equivalent to 1 in Python, so usually add the True or non-zero values in the array to get the sum of values in the array that matches the condition.
Python3
import numpy as np arr = np.array([ 2 , 3 , 4 , 5 , 3 , 3 , 5 , 4 , 7 , 8 , 3 ]) print ( 'Numpy Array:' ) print (arr) # Count '3' in array count = (arr = = 3 ). sum () print ( 'Occurrences of "3" in array: ' , count) |
Output:
Numpy Array: [2 3 4 5 3 3 5 4 7 8 3] Occurrences of "3" in array: 4
Count the occurrence of a certain item in an ndarray – Numpy
In this article, the task is to find out how to count the occurrence of a certain item in an nd-Array in Python.
Example
Array = [[ 0 1 2 3] [ 4 5 2 7] [ 8 2 10 11]] Input: element = 2 Output: 3 times