How Can I Find The Duration A List Element Exceeds A Certain Criteria?
I'm analysing EEG data for my honours project. Specifically, I'm analysing EEG bursts (i.e. the number of counts that it exceeds a criteria). The EEG values are recorded every seco
Solution 1:
You can get these regions using numpy. I leveraged part of an answer from another question to do this.
Results with index positions and number of points between them as well as screenshot of console/plot:
The code to do this (You had no data given, I used a sine-wave as base):
import numpy as np
import datetime
import matplotlib.pyplot as plot
base = datetime.datetime(2019, 1, 1,8,0,0)
tarr = np.array([base + datetime.timedelta(seconds=i) for i inrange(60*60)]) # 1 h
time = np.arange(0, 6*6, 0.01) *0.2;
amp = np.sin(time)
# get all indexes that interest me - yours would have the mean here# not used in rest of code: contains all indexes that are above 0.75
indx = np.nonzero(abs(amp) > 0.75)
# looks like: (array([ 425, 426, 427, ..., 3597, 3598, 3599], dtype=int64),)defcontiguous_regions(cond):
"""Credits: https://stackoverflow.com/a/4495197/7505395""""""Finds contiguous True regions of the boolean array "condition". Returns
a 2D array where the first column is the start index of the region and the
second column is the end index."""# Find the indicies of changes in "condition"
d = np.diff(cond)
idx, = d.nonzero()
# We need to start things after the change in "condition". Therefore, # we'll shift the index by 1 to the right.
idx += 1if condition[0]:
# If the start of condition is True prepend a 0
idx = np.r_[0, idx]
if condition[-1]:
# If the end of condition is True, append the length of the array
idx = np.r_[idx, cond.size]
# Reshape the result into two columns
idx.shape = (-1,2)
return idx
condition = np.abs(amp) > 0.75# create a plot visualization
fig, ax = plot.subplots()
ax.plot(tarr, amp)
# print values that fullfill our condition - also do some plottingfor start, stop in contiguous_regions(condition):
segment = amp[start:stop]
print (start, stop, f"Amount: {stop-start}")
# plot some lines into the graph, off by 1 for stops in graph
ax.vlines(x=tarr[start], ymin=amp[start]+(-0.1if amp[start]>0else0.1),
ymax=1.0if amp[start]>0else -1.0, color='r')
ax.vlines(x=tarr[stop-1], ymin=amp[start]+(-0.1if amp[start]>0else0.1),
ymax=1.0if amp[start]>0else -1.0, color='r')
ax.hlines(y=amp[start]-0.08,xmin=tarr[start],xmax=tarr[stop-1])
# show plot
plot.show()
The trick is to apply ndp.diff to the array with [False,True,...]
's in them that fullfill the condition. Then get the indexes from np.nonzero()
result-tuple.
Post a Comment for "How Can I Find The Duration A List Element Exceeds A Certain Criteria?"