How to find the number of occurrence of matrix element with numpy in python ?

Published: March 02, 2021

Tags: Python; Numpy;

DMCA.com Protection Status

Examples of how to find the number of occurrence of a given element in a matrix with numpy in python ?

Create a random matrix with numpy

Let's create a random matrix of size (4,4) with random integers between 0 and 4:

import numpy as np

A = np.random.randint(0,5,(4,4))

returns for example

[[3 0 2 2]
 [1 3 4 2]
 [0 0 3 1]
 [2 3 3 1]]

Find the number of occurrences for each item

To find the number of occurrences for each element one solution is to use the numpy function "unique":

unique, counts = np.unique(A, return_counts=True)

for i in range(len(unique)):
    print(unique[i],counts[i])

returns

0 3
1 3
2 4
3 5
4 1

It is then possible to create a dictionary

dict(zip(unique, counts))

returns

{0: 3, 1: 3, 2: 4, 3: 5, 4: 1}

Find the number of occurrences for a given element using where

Another solution to find the occurrence number of 3 using where:

np.where(A==3)[0].shape[0]

returns

5

Find the number of occurrences for a given element using the collections module

Another example of how to find the number of occurrences of a given element in an array

import collections

collections.Counter(A.ravel())

returns

Counter({3: 5, 0: 3, 2: 4, 1: 3, 4: 1})

References