Pete Lavelle
Pete Lavelle

Reputation: 103

iterate through an array looking at non-consecutive values

for i,(x,y,z) in enumerate( zip(analysisValues, analysisValues[1:], analysisValues[2:]) ):
    if all(k<0.5 for k in (x,y,z)):
        instance = i
        break

this code iterates through an array and looks for the first 3 consecutive values that meet the condition '<0.5'

==============================

i'm working with 'timeseries' data and comparing the values at t, t+1s and t+2s

if the data is sampled at 1Hz then 3 consecutive values are compared and the code above is correct (points 0,1,2)

if the data is sampled at 2Hz then every other point must be compared (points 0,2,4) or if the data is sampled at 3Hz then every third point must be compared (points 0,3,6)

the sample rate of input data can vary, but is known and recorded as the variable 'SRate'

==============================

please can you help me incorporate 'time' into this point-by-point analysis

Upvotes: 1

Views: 190

Answers (2)

ovgolovin
ovgolovin

Reputation: 13410

Let us first construct helper generator which does the following:

from itertools import izip, tee, ifilter

def sparsed_window(iterator, elements=2, step=1):
    its = tee(iterator, elements)
    for i,it in enumerate(its):
        for _ in range(i*step):
            next(it,None) # wind forward each iterator for the needed number of items

    return izip(*its)

print list(sparsed_window([1,2,3,4,5,6,7,8,9,10],3,2))

Output:

>>> 
[(1, 3, 5), (2, 4, 6), (3, 5, 7), (4, 6, 8), (5, 7, 9), (6, 8, 10)]

This helper avoids us of creating nearly the same lists in memory. It uses tee to clever cache only the part that is needed.

The helper code is based on pairwise recipe

Then we can use this helper to get what we want:

def find_instance(iterator, hz=1):
    iterated_in_sparsed_window = sparsed_window(iterator, elements=3, step=hz)
    fitting_values = ifilter(lambda (i,els): all(el<0.5 for el in els), enumerate(iterated_in_sparsed_window))
    i, first_fitting = next(fitting_values, (None,None))
    return i

print find_instance([1,0.4,1,0.4,1,0.4,1,0.4,1], hz=2)

Output:

>>> 
1

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213223

You can use extended slice notation, giving the step value as SRate:

for i,(x,y,z) in enumerate(zip(analysisValues, \
                               analysisValues[SRate::SRate], \
                               analysisValues[2 * SRate::SRate])):

Upvotes: 1

Related Questions