'Avoid for-loops when getting mean of every positive-value-interval in an array
I want to get the mean of every interval with values above a threshold. Obviously, I could do a loop and just look if the next value is under the threshold etc., but I was hoping that there would be an easier way. Do you have ideas that are similar to something like masking, but include the "interval"-problem?
Below are 2 pictures with the original data and what I want to obtain.
Before:
After:
My original idea was looping through my array, but as I want to do this about 10.000 times or more, I guess it's getting very time intensive.
Is there a way to get rid of the for loops?
transformed is a numpy array.
plt.figure()
plt.plot(transformed)
thresh=np.percentile(transformed,30)
plt.hlines(np.percentile(transformed,30),0,700)
transformed_copy=transformed
transformed_mask=[True if x>thresh else False for x in transformed_copy]
mean_arr=[]
for k in range(0,len(transformed)):
if transformed_mask[k]==False:
mean_all=np.mean(transformed_copy[mean_arr])
for el in mean_arr:
transformed_copy[el]=mean_all
mean_arr=[]
if transformed_mask[k]==True:
mean_arr.append(k)
plt.plot(transformed_copy)
Output after loop:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|



