0

I have a numpy array that looks like this: [1 -1 -1 1 1 1 -1 -1 -1 1 -1 -1 1 -1]

How do i find the location of the sequence [1 1 1 -1] ?

The output of the function should be something like: Occurrence = 3, since the sequence starts at index 3.

Thanks for helping me!

  • Why a simple loop does not work? – OmG Oct 07 '19 at 10:00
  • Possible duplicate of [Find indexes of sequence in list in python](https://stackoverflow.com/questions/10459493/find-indexes-of-sequence-in-list-in-python) – tfw Oct 07 '19 at 10:07
  • I get: "The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()" when using that – Mikkel Juul Jørgensen Oct 07 '19 at 10:08
  • Possible duplicate of [Searching a sequence in a NumPy array](https://stackoverflow.com/questions/36522220/searching-a-sequence-in-a-numpy-array) – FObersteiner Oct 07 '19 at 11:24
  • 2
    check [Divakar's answer](https://stackoverflow.com/a/36535397/10197418) from the dupe link - his function is about twice as fast as the [list-based accepted answer](https://stackoverflow.com/a/58267522/10197418) here (on my machine; use `timeit` to check for yourself). – FObersteiner Oct 07 '19 at 11:30

2 Answers2

0

If you have other range of numbers, a double loop will work ...

def subindex(sub, arr):
    index = i = -1  # or None or whatever is relevant when sub is NOT found
    ext_arr = list(arr)
    ext_arr.extend([np.NaN]*len(sub))
    for j, sub_j in enumerate(sub):
        for i, arr_i in enumerate(ext_arr[j:j+len(sub)]):
            try:
                if arr_i != sub_j:
                    continue  # get out of the inner loop and check from next i
            except:
                pass
        # if you are here, you have a match
        index = i
        break
    return index

Result ...

>>> arr = "1 -1 -1 1 1 1 -1 -1 -1 1 -1 -1 1 -1".split(" ")
>>> sub = "1 1 1 -1".split()
>>> print(subindex(sub, arr))
3
Cedric Druck
  • 1,032
  • 7
  • 20
0

In one line :

[i for i in range(0,len(x)) if list(x[i:i+4])==[1, 1, 1, -1]]

[3]

IF you want a general solution:

#define your np.array and your list
x=np.array([1 ,-1, -1 ,1 ,1 ,1, -1, -1, -1 ,1, -1, -1, 1 ,-1])
sublist=[1, 1, 1, -1]

[i for i in range(0,len(x)) if list(x[i:i+len(sublist)])==sublist]

[3]
Billy Bonaros
  • 1,671
  • 11
  • 18