在 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.
下面是一个例子的实现:
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)
输出 :
4