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)
Amri Rasyidi
  • 172
  • 1
  • 10
Felix
  • 11
  • 2
  • Have you read [this](https://stackoverflow.com/questions/36004976/count-frequency-of-values-in-pandas-dataframe-column)? – Amri Rasyidi Apr 22 '21 at 08:52
  • `np.where(rain_15Min[:]== 0)` will give you the 0 points, then you can reason from there – Alex Apr 22 '21 at 10:07

1 Answers1

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]
innohead
  • 344
  • 2
  • 3