1

I would like to build something like this if statements into a numpy condition (for argwhere or similar).

for i, element in enumerate(array):
    if array[i]+1 == array[i+1]:
        return True 

Is this possible or is looping through the array the only way?

1
  • See speed considerations below in my answer Commented Nov 25, 2019 at 12:05

2 Answers 2

3

You can use the np.roll function that shifts the array

import numpy as np
array+1 == np.roll(array, shift=-1)

This will return an array of boolean values.

Sign up to request clarification or add additional context in comments.

6 Comments

You meant shift = -1
np.roll([1,2,3,4,], shift=1) is array([4, 1, 2, 3]). So you should know that last element compares with first.
thank you very much I think that is exactly the right answer
@Aryerez See speed considerations below in my answer
@Geeocode I have change my answer since like you say it is a faster method and you included a comparison. But I ask that you include a reference to FBruzzesi since you are comparing to his answer.
|
2

You can use np.equal() function as well.

import numpy as np

a = [1,2,4,8,12,13]
x = np.array(a)
res = np.equal((x+1)[:-1], x[1:])

print(res)

Out:

[ True False False False  True]

Note:

If you need speed, as it is usual the case, when we use numpy, it is worth to mention, that this methode is faster then np.roll(), what FBruzzesi proposed below and which is an elegant solution as well anyway:

import timeit

code1 = """
import numpy as np
a = [1,2,4,8,12,13]
x = np.array(a)
np.equal((x+1)[:-1], x[1:])
"""
elapsed_time1 = timeit.timeit(code1, number=10000)/100
print(elapsed_time1)

code2 = """
import numpy as np
a = [1,2,4,8,12,13]
x = np.array(a)
x+1 == np.roll(x, shift=-1)
"""

elapsed_time2 = timeit.timeit(code2, number=10000)/100
print(elapsed_time2)

Out:

0.00044608700000026147
0.0022752689999970244

Comments

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.