pythonarraysnumpycumsum

How to count consecutive increases in a 1d array


import numpy as np

def count_consecutive_increases(y: np.ndarray) -> np.ndarray:
    ...

y = np.array([9, 8, 7, 9, 6, 5, 6, 7, 8, 4, 3, 1, 2, 3, 0])
c = count_consecutive_increases(y)

print(y)
print(c)

# >>> [9 8 7 9 6 5 6 7 8 4 3 1 2 3 0]
# >>> [0 0 0 1 0 0 1 2 3 0 0 0 1 2 0]

Solution

  • Here is another solution:

    import numpy as np
    
    def count_consecutive_increases(y: np.ndarray) -> np.ndarray:
        increases = np.diff(y, prepend=y[0]) > 0
        all_summed = np.cumsum(increases)
        return all_summed - np.maximum.accumulate(all_summed * ~increases)
    
    y = np.array([9, 8, 7, 9, 6, 5, 6, 7, 8, 4, 3, 1, 2, 3, 0])
    c = count_consecutive_increases(y)
    
    print(y)  # >>> [9 8 7 9 6 5 6 7 8 4 3 1 2 3 0]
    print(c)  # >>> [0 0 0 1 0 0 1 2 3 0 0 0 1 2 0]
    

    The idea is the same as with the solution proposed by OP, albeit a bit shorter: Naively count (by summing over) all indices that have been marked as increasing, then subtract, for each consecutive increasing segment, the count right before its start (the value of which we get by a cumulative maximum over the naive counts at the positions marked as not increasing).