Search code examples
pythonarraysnumpymaxindices

Finding the maximum in a Numpy array every nth instance


I have a large file with wind speed and direction every second. I have stored each element into a numpy array. The wind speeds for example are ws=(7, 8, 8.5, 8, 9.5). I would like to fill another array with the maximum 1 minute wind speed, so every 60 instances, I need to pull the max. I have tried this:

gust = np.full(len(ws), 0) 
indices = sig.argrelmax(ws)
gust[indices] = ws[indices]

his arbitrarily pulls out maximums and enters them successfully into an array while maintaining the same index they had in the ws array, but 1) I need it to check for maximum in batches of 60 (1-60, 61-120,...etc). 2) It turns the number in an integer and I need floats to remain as floats.


Solution

  • If you want to handle non multiples of 60 in a more direct way you can use reduceat:

    wind=np.random.normal(size=1000)
    res=np.maximum.reduceat(wind, np.r_[:wind.size:60])
    

    np.r_ creates an array of indices 0,60,120...

    reduceat performs the ufunc maximum at the slices between consecutive indices

    And so the last element of res is the max of the last 1000%60 elements of wind