2

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 ?

1 Answer 1

6

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])
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant, thanks ! That was just what I was looking for. Simple once you see it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.