简体   繁体   中英

Python: find onset and length of a specific pattern in list

Consider a list of zeros and ones, where ones represent "events":

signal = [0,0,0,0, 1,1, 0,0,0, 1,1,1, 0,0,0, 1, 0,0, 1,1,1,1, 0]

Here we have 4 events of different durations. What is the most pythonic and neat way to get the onset ( ie, the index of the first "1") and the duration ( ie, the number of ones) of each of these events?

I've tried iterating over the list but I cannot find a way to find the duration?

You can use itertools.groupby to group the consecutive events together and count the 1s. It is memory efficient and fast.

from itertools import groupby

signals = [0,0,0,0,1,1,0,0,0,1,1,1,0,0,0,1,0,0,1,1,1,1,0]

def count_event(signals,event_value=1):
    """Counts no of events and counts the duration of the events

    Args:
        signal : list of signals
        event_value : value of the siganl

    Returns:
        list of tuples of index and duration of events
    """
    event_duration = []
    index = 0
    for key,g in (groupby(signal)):
        length = len(list(g))
        if key == event_value:
            event_duration.append((index,length))
        index += length
    return event_duration

print(count_event(signal,1))

Output:

[(4, 2), (9, 3), (15, 1), (18, 4)]

You can use itertools.groupby . I put the onset , duration pair in a list of tuples, but you could use any data structure you will later find convenient:

>>> import itertools
>>> from operator import itemgetter
>>> gb = itertools.groupby(enumerate(signal), itemgetter(1))
>>> signals = []
>>> for k, g in gb:
...     if k:
...         sig = list(g)
...         onset = sig[0][0]
...         duration = len(sig)
...         signals.append((onset, duration))
...
>>> signals
[(4, 2), (9, 3), (15, 1), (18, 4)]
from pylab import *
x = array([0,0,0,0,1,1,0,0,0,1,1,1,0,0,0,1,0,0,1,1,1,1,0])
plus = where(x[1:] - x[:-1] > 0)[0]
minus = where(x[1:] - x[:-1] < 0)[0]
print vstack((plus + 1, minus -plus)).T

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM