Search code examples
pythonpython-2.7numpy

Finding Patterns in a Numpy 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.

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.

Example:

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]

Output:

[]

Expected Output:

[1, 3, 8]

Solution

  • 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)