Search code examples
pythonarraysnumpyvectorization

Vectorizing iterative array slicing in Numpy/Python


I am trying to vectorize a numpy loop-process in which I iteratively slice an array with each loop:

for y in range(0, 10):
    maxpr[y] = npds[y*365:(y+1)*365].max(axis=0)

npds is a (3650, 192, 288) numpy array while maxpr is a (10,192,288) numpy array.

I am effectively trying to get rid of this for loop that iterates y through vectorization.

I have already tried something like:

years1 = np.arange(0,3650,365)
years2 = years1 + 365

maxpr = npds[years1:years2].argmax(axis=0)

but this returns an error of "only integer scalar arrays can be converted to a scalar index".

Please let me know if you have any suggestions; thank you.


Solution

  • You can break the first dimension into 2, i.e. reshape the array to (10, 365, 192, 288) and then max along 2nd axis:

    npds.reshape((10, 365, 192, 288)).max(axis=1)
    

    Example:

    npds = np.arange(24).reshape((6,2,2))
    maxpr = np.empty((3,2,2))
    
    for y in range(0, 3):
        maxpr[y] = npds[y*2:(y+1)*2].max(axis=0)
    
    (npds.reshape((3,2,2,2)).max(axis=1) == maxpr).all()
    # True