Python – Numpy finds elements that are larger than the first n elements

Numpy finds elements that are larger than the first n elements… here is a solution to the problem.

Numpy finds elements that are larger than the first n elements

I want to identify elements in a numpy array that are larger than the first 5 elements starting at index 5. I wrote the solution to this problem using a “for” loop below. My question is how to solve a similar problem without iterating? Is there a specific numpy function for this issue?

import numpy as np
values = np.array([160, 140, 152, 142, 143, 186, 152, 145, 165, 152, 143, 148, 196, 152, 145, 157, 152])
indices = []
for i in range(5, len(values)):
    if np.all(values[(i-5):i]<values[i]):
        indices.append(i)

Solution

One trick is to calculate the maximum value in the sliding window of the array length, excluding the current element and comparing it with the current element. If the current element is larger, we have a winner, otherwise we don’t.

To get the sliding maximum, we can take advantage of Scipy's 1D max's service filter, so there is an implementation like this-

from scipy.ndimage.filters import maximum_filter1d as maxf

def greater_than_all_prev(values, W=5):
    hW = (W-1)//2
    maxv = maxf(values,W, origin=hW)
    mask = values[1:] > maxv[:-1]
    mask[:W-1] = 0
    return np.flatnonzero(mask)+1

sample run-

In [336]: values
Out[336]: 
array([160, 140, 152, 142, 143, 186, 152, 145, 165, 152, 143, 148, 196,
       152, 145, 157, 152])

In [337]: greater_than_all_prev(values, W=5)
Out[337]: array([ 5, 12])

Related Problems and Solutions