在一个Numpy数组中查找模式 [英] Finding Patterns in a Numpy Array

查看:94
本文介绍了在一个Numpy数组中查找模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在称为valuesnumpy array中查找模式.我想返回模式的起始索引位置.我知道我可以遍历每个元素并检查该元素和下一个元素是否与模式匹配,但是要遍历一个效率极低且正在寻找更好替代方法的大型数据集.

I am trying to find patterns in a numpy array, called values. I'd like to return the starting index position of the pattern. I know I could iterative over each element and check whether that element and the next one match the pattern, but over a large dataset that is incredibly inefficient and am looking for a better alternative.

我有一个使用np.where的有效解决方案来搜索单个值,但是我无法将其用于查找模式或两个数字.

I've got a working solution using np.where for searching for a single value, but I can't get it to work with finding a pattern or two numbers.

示例:

import numpy as np
values = np.array([0,1,2,1,2,4,5,6,1,2,1])
searchval = [1,2]
print  np.where(values == searchval)[0]

输出:

[]

预期输出:

[1, 3, 8]

推荐答案

您不能简单地使用np.where(假设这是查找元素的最佳方法),然后仅检查满足第一个条件的图案. /p>

Couldn't you simply use np.where (assuming this is the optimal way to find an element) and then only check pattens which satisfy the first condition.

import numpy as np
values = np.array([0,1,2,1,2,4,5,6,1,2,1])
searchval = [1,2]
N = len(searchval)
possibles = np.where(values == searchval[0])[0]

solns = []
for p in possibles:
    check = values[p:p+N]
    if np.all(check == searchval):
        solns.append(p)

print(solns)

这篇关于在一个Numpy数组中查找模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆