Compare adjacent values in numpy array
Question: I have a Numpy one-dimensional array of data, something like this

    
    
    a = [1.9, 2.3, 2.1, 2.5, 2.7, 3.0, 3.3, 3.2, 3.1]
    

I want to create a new array, where the values are composed of the greater of
the adjacent values. For the above example, the output would be:

    
    
    b = [2.3, 2.3, 2.5, 2.7, 3.0, 3.3, 3.3, 3.2]
    

I can do this by looping through the input array, comparing the neighbouring
values, eg:

    
    
    import numpy as np
    
    a = np.array([1.9, 2.3, 2.1, 2.5, 2.7, 3.0, 3.3, 3.2, 3.1])
    b = np.zeros(len(a)-1)
    
    for i in range(len(a)-1):
        if (a[i] > a[i+1]):
            b[i] = a[i]
        else:
            b[i] = a[i+1]
    

but I'd like to do this in a more elegant "pythonic" vectorised fashion. I've
searched and read about np.zip, np.where, np.diff etc but haven't yet found a
way to do this (or more likely, I haven't understood what is possible). Any
suggestions ?


Answer: You want element-wise maximum of `a[1:]` and `a[:-1]`:

    
    
    >>> a
    array([ 1.9,  2.3,  2.1,  2.5,  2.7,  3. ,  3.3,  3.2,  3.1])
    >>> a[1:]
    array([ 2.3,  2.1,  2.5,  2.7,  3. ,  3.3,  3.2,  3.1])
    >>> a[:-1]
    array([ 1.9,  2.3,  2.1,  2.5,  2.7,  3. ,  3.3,  3.2])
    >>> np.maximum(a[1:], a[:-1])
    array([ 2.3,  2.3,  2.5,  2.7,  3. ,  3.3,  3.3,  3.2])
    

