1

I am trying to code a python code to get the number of times non-zero value occur continuously between the zero values. To count frequency and store the non zero number which occur once, between zero in the array is easy and simple. But problem arises when I try to code for non zero that occurs more than 6 continuously, that is the code starts getting too lengthy. Here is what I have tried

rain_15Min = np.array([0,15,15,15,4,0,5,5,5,90,0,30,4,3,30,32,0,0,45,45,45,4,50,0,3,4,5,0,0,0,6,7,5,5])
R_75min=[]
# for 75 Minutes duration    
for i in range(len(rain_15Min)-5): 
    if rain_15Min[i]!= 0 and rain_15Min[i-1]== 0 and rain_15Min[i+1] !=0 and rain_15Min[i+2] !=0 and rain_15Min[i+3] !=0 and rain_15Min[i+4] !=0 and rain_15Min[i+5] == 0:
        R_75min.append(rain_15Min[i:i+5])
print("The frequency of 60min rainfall is: ")
print(len(R_75min))
print(R_75min)
2
  • Have you read this? Commented Apr 22, 2021 at 8:52
  • np.where(rain_15Min[:]== 0) will give you the 0 points, then you can reason from there Commented Apr 22, 2021 at 10:07

1 Answer 1

1

One could use a generator.

def chunker(items):
    chunk = []
    for item in items:
        if item != 0:
            chunk.append(item)
        else:
            if chunk:
                yield chunk
                chunk = []
    if chunk:
        yield chunk

            
rain_15Min = [0,15,15,15,4,0,5,5,5,90,0,30,4,3,30,32,0,0,45,45,45,4,50,0,3,4,5,0,0,0,6,7,5,5]

chunks = [chunk for chunk in chunker(rain_15Min)]
chunk_lens = [len(chunk) for chunk in chunks]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.