Sunday, November 17, 2024
Google search engine
HomeLanguagesFind the number of occurrences of a sequence in a NumPy array

Find the number of occurrences of a sequence in a NumPy array

The sequence is consisting of some elements in the form of a list and we have to find the number of occurrences of that sequence in a given NumPy array. This can be done easily by checking the sequence for every iteration of ndarray. But this leads to higher time so we use the concept of NumPy methods.

Example :

Arr = [[2,8,9,4],
       [9,4,9,4],
       [4,5,9,7],
       [2,9,4,3]]
and the seq = [9,4] then output is 4.

Here, 
first row [2,8,9,4] 
contains one [9,4] sequence so output = 1.

second row [9,4,9,4] 
contains two [9,4] sequence so output = 1+2 = 3.

third row [4,5,9,7] 
contains no [9,4] sequence so output = 3+0 = 3.

fourth row [2,9,4,3] 
contains one [9,4] sequence so output = 3+1 = 4.

Below is the implementation with an example :

Python3




# importing package
import numpy
  
# create numpy array
arr = numpy.array([[2, 8, 9, 4], 
                   [9, 4, 9, 4],
                   [4, 5, 9, 7],
                   [2, 9, 4, 3]])
  
# Counting sequence
output = repr(arr).count("9, 4")
  
# view output
print(output)


Output :

4
RELATED ARTICLES

Most Popular

Recent Comments