![]() |
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 Count the occurrence of a certain item in an array using a loopHere we are using a loop to count the occurrence of an element in an array. Python3
Output: Numpy Array:[2 3 4 5 3 3 5 4 7 8 3] element occurred 4 times Count the occurrence of a certain item in an array using count_nonzero()Here we are using the count_nonzero() function to count the occurrence of an item in the array if the match the target value. Example 1:For 1D array Python3
Output: Numpy Array: [2 3 4 5 3 3 5 4 7 8 3] Total occurrences of "3" in array: 4 Example 2:For 2D array Python3
Output: Numpy Array: [[1 3 6] [1 3 4] [5 3 6] [4 7 8] [3 6 1]] Occurrences of "3" in array: 4 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
Output: Numpy Array: [2 3 4 5 3 3 5 4 7 8 3] Occurrences of "3" in array: 4 Counting the matching value to count the occurrence of an itemHere we are using the concept of matching the value present in the array and finding the occurrence of that element in the array. Python3
Output: Occurrences of "3" in array is: 4 Count the occurrence of a certain item in an array using the tolist()Here we are converting the Numpy array into a list using the tolist() and then counting the number of elements that match the target elements. Python3
Output: Occurrences of "3" in array: 2 |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 9 |