We can either use count_nonzero or where with len function to count the occurenece of a certain item in a Numbpy ndarray in Python.
Below is the example using both functions:
import numpy as np
arr = np.array([1, 2, 3, 1, 4, 1, 5])
item_to_count = 1
count = np.count_nonzero(arr == item_to_count)
print(f"The number 1 occurs {count} times -- Using count_nonzero function")
count2 = len(np.where(arr == item_to_count)[0])
Print(f”The number 1 occurs {count2} times -- Using where function”)
Output:
The number 1 occurs 3 times -- Using count_nonzero function
The number 1 occurs 3 times -- Using where function