查找NumPy数组中一个序列的出现次数
序列是由一些元素组成的列表,我们必须找到该序列在一个给定的NumPy数组中出现的次数。这可以通过在ndarray的每一次迭代中检查序列来轻松完成。但是这将导致更多的时间,所以我们使用NumPy方法的概念。
示例 :
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.
下面是一个例子的实现。
# 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)
输出 :
4