Skip to content
Related Articles

Related Articles

Find the number of occurrences of a sequence in a NumPy array
  • Last Updated : 05 Sep, 2020
GeeksforGeeks - Summer Carnival Banner

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

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :