Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: numpy array sublist match with large list where sequence matter

Tags:

python

numpy

I need to find in which index in the large list where it match with the sub list.

c = np.array(close)
EMA50 = np.array(MA50)
sublist = [False,True,True]
biglist = (c-EMA50)/c>0.01
>>>array([False, False, False, False, False, False, False, False, False,
       False, False, False, False,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True, False, False,  True, False,  True,  True, False, False,
        True, False, False, False, False, False, False, False,  True,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False,  True,  True,  True,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False,  True,  True,  True,  True], dtype=bool)
>>>sublist in biglist
>>>False

I expected True but it return False.

The desired output is

index_loc = [12,31,68,112] 
like image 200
bkcollection Avatar asked Oct 29 '22 12:10

bkcollection


1 Answers

One very easy solution using the sublist pattern for slicing and checking for that signature and getting the indices would be -

np.flatnonzero(~a[:-2] & a[1:-1] & a[2:]) # a as data array

Explanation

Basically, we are slicing three slices out of the data array - One that starts at 0th index and goes until leaving out last two elements, another that starts at 1st index and ends at second last element and a third slice starting at 2nd and goes on until the end. These three slices correspond to the three elements of matching required against the sublist pattern that's - [False, True, True]. We need to make sure that the first one is False, in other words, let's make sure the negation of it is True. Negation in NumPy is achieved through ~ operator. So, in essence, we get the combined mask off those three slices and get the corresponding indices with np.flatnonzero.

For the given data results in -

In [79]: np.flatnonzero(~a[:-2] & a[1:-1] & a[2:])
Out[79]: array([ 12,  31,  68, 112])
like image 59
Divakar Avatar answered Nov 15 '22 07:11

Divakar