考虑一个零和一的列表,其中一个代表“事件”:
signal = [0,0,0,0, 1,1, 0,0,0, 1,1,1, 0,0,0, 1, 0,0, 1,1,1,1, 0]
这里我们有4个不同持续时间的事件。什么是获得开始的最pythonic和整洁的方式(即第一个“1”的索引)和持续时间(即的数量)这些事件中的每一个?
我试过迭代列表,但我找不到找到持续时间的方法吗?
答案 0 :(得分:1)
您可以使用itertools.groupby
将连续事件分组在一起并计算1。它内存效率高,速度快。
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))
输出:
[(4, 2), (9, 3), (15, 1), (18, 4)]
答案 1 :(得分:1)
您可以使用itertools.groupby
。我将onset
,duration
对放在元组列表中,但您可以使用以后会方便的任何数据结构:
>>> 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)]
答案 2 :(得分:0)
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