numpy:在较大的数组B中搜索具有相同模式的数组A [英] Numpy: Search for an array A with same pattern in a larger array B
问题描述
我有两个一维numpy数组A(小)和B(大)
I have two 1D numpy array A(small) and B(large)
A=np.array([6,7,8,9,10])
B=np.array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,10])
我想检查数组A中的元素是否与数组B中检测到的顺序相同. 从我们检测到数组A起始处的位置获取数组B的索引值
I want to check if we have elements of the array A in the same order being detected in the array B. Get the index value of array B from where the we detect the starting of array A
Index Value returned = 6
我们有内置的numpy函数来执行这种操作吗?
Do we have any inbuilt numpy function to perform such an operation?
推荐答案
我找到了一个不错的解决方案.
I found a nice solution.
由@EdSmith在在一个Numpy数组中查找模式给出
Given by @EdSmith in Finding Patterns in a Numpy Array
简而言之,就是这个过程
In short this is the process
- 缩短要搜索的数组的长度.(我的示例A)
- 使用np.where和np.all检查要搜索的数组的整个长度(我的示例B)
这不是我的代码,而是可以在about链接中找到的代码,简单易行.我将对其稍作修改,以使其适合上面的示例,希望它对某人有帮助:)
This is not my code but the code that can be found in the about link, Simple and easy. I'll just alter it a bit to fit my example above Hope it helps someone :)
感谢@EdSmith
Thanks to @EdSmith
import numpy as np
A=np.array([6,7,8,9,10])
B=np.array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,10])
N = len(A)
possibles = np.where(B == A[0])[0]
solns = []
for p in possibles:
check = B[p:p+N]
if np.all(check == A):
solns.append(p)
print(solns)
输出
[6]
这篇关于numpy:在较大的数组B中搜索具有相同模式的数组A的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!