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!

5
  • Why a simple loop does not work? Commented Oct 7, 2019 at 10:00
  • Possible duplicate of Find indexes of sequence in list in python Commented Oct 7, 2019 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 Commented Oct 7, 2019 at 10:08
  • Possible duplicate of Searching a sequence in a NumPy array Commented Oct 7, 2019 at 11:24
  • 2
    check Divakar's answer from the dupe link - his function is about twice as fast as the list-based accepted answer here (on my machine; use timeit to check for yourself). Commented Oct 7, 2019 at 11:30

2 Answers 2

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]
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.