I am looking for an easy way to find "plateau" or groups in python lists. As input, I have something like this:
mydata = [0.0, 0.0, 0.0, 0.0, 0.0, 0.143, 0.0, 0.22, 0.135, 0.44, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.33, 0.65, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0]
I want to extract the middle position of each "group." the group is defined in this case as data equal to! = 0 and, for example, at least 3 positions. Closed single zeros (e.g. at position 6) should be ignored.
Basically I want to get the following output:
myoutput = [8, 20]
In my use case, it is not very important to get very accurate output. [10,21]all the same it will be good.
In conclusion, all: first group [0.143, 0.0, 0.22, 0.135, 0.44, 0.1]:; The second group: [0.33, 0.65, 0.22]. now the position of the middle element (either to the left or to the right of the middle if there is no true average value). therefore, the output 8would be the middle of the first group, and 20- the environment of the second group.
I have already tried some approaches. But they are not as stable as I wanted them to be (for example: narrower zeros can cause problems). Therefore, before investing more time in this idea, I wanted to ask if there is a better way to implement this function. I even think that this can be a common problem. Maybe already the standard code that solves it?
There are other questions that describe roughly the same problem, but I also need to “smooth out” the data before processing.
1.) -
import numpy as np
def smooth(y, box_pts):
box = np.ones(box_pts)/box_pts
y_smooth = np.convolve(y, box, mode='same')
return y_smooth
y_smooth = smooth(mydata, 20)
2.) ( != 0, before 0, ). : , deque.
laststart = 0
lastend = 0
myoutput = deque()
for i in range(1, len(y_smooth)-1):
if y_smooth[i]!=0 and y_smooth[i-1]==0:
laststart = i
elif y_smooth[i]!=0 and y_smooth[i+1]==0 and laststart+2 < i:
lastend = i
myoutput.appendleft(laststart+(lastend-laststart)/2)
EDIT: , . - , . ;