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
import numpy
arr = numpy.array([[ 2 , 8 , 9 , 4 ],
[ 9 , 4 , 9 , 4 ],
[ 4 , 5 , 9 , 7 ],
[ 2 , 9 , 4 , 3 ]])
output = repr (arr).count( "9, 4" )
print (output)
|
Output :
4
Last Updated :
05 Sep, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...