I need to filter out short nonzero series, that lies between zeros. For example, this array:
t = np.array([1, 3, 1, 0, 0, 1, 8, 3, 0, 8, 2, 4, 7, 0,0,4,1])
should become:
array([1, 3, 1, 0, 0, 0, 0, 0, 0, 8, 2, 4, 7, 0, 0, 4, 1])
I found the first indices of non zero sequanceses, and counted num of non zeros between them. I wrote the following, It works, but look awful. I tried staf but got an errors. How to rewrite it pythonicly ?
minseq = 4 # length of minimal non zero seq
p = np.where(fhr>0, 1, 0).astype(int)
s = np.array([1]+ list(np.diff(p)))
sind = np.where(s==1)[0][1:]
print(sind)
for i in range(len(sind) - 1):
s1 = sind[i]
e1 = sind[i+1]
subfhr = np.where(fhr[s1:e1] > 0, 1, 0).sum()
if (subfhr < minseq):
print(s1, e1, subfhr)
fhr[s1:e1] = 0
out:
[ 5 9 15]
5 9 3
array([1, 3, 1, 0, 0, 0, 0, 0, 0, 8, 2, 4, 7, 0, 0, 4, 1])