0

I have a numpy array such as

import numpy as np
x = np.array(range(1, 10))

assuming that x is a 'timeseries' I am testing for truthiness on 2 conditions, if x t is larger than 5 and x t-1 is larger than 5 at the same time

is there a more pythonic way to write this test:

np.where((x[1:] > 5) & (x[0:-1] > 5), 1, 0)
array([0, 0, 0, 0, 0, 1, 1, 1])

I feel like calling x[1:] and x[0:-1] to get a lag value is kind of weird.

any better way?

thanks!

4
  • 1
    FYI: You don't need to use where(...). The expression (x[1:] > 5) & (x[0:-1] > 5) is a boolean array that you could probably use in place of the where(...) result, or, if you need integers, convert using the .astype(int) method: ((x[1:] > 5) & (x[0:-1] > 5)).astype(int). Commented Dec 16, 2016 at 19:53
  • @WarrenWeckesser good point! thanks. Commented Dec 16, 2016 at 19:57
  • I wouldn't call your expression "weird"; using shifted slices like that is pretty common in numpy code. There is some inefficiency, because you are repeating the same comparison len(x) - 1 times. For a small array, it might not matter, but if in your actual code x can be much larger, you could do something like: xgt5 = x > 5; result = xgt5[1:] & xgt5[:-1] Commented Dec 16, 2016 at 20:02
  • Yes my real arrays are much larger. I tested for speed, and your solution is about 2times faster. I can accept it as the answer if you want to post it below! Commented Dec 16, 2016 at 20:06

1 Answer 1

1

I wouldn't call your expression "weird"; using shifted slices like that is pretty common in numpy code. There is some inefficiency, because you are repeating the same comparison len(x) - 1 times. For a small array, it might not matter, but if in your actual code x can be much larger, you could do something like:

xgt5 = x > 5
result = xgt5[1:] & xgt5[:-1]
Sign up to request clarification or add additional context in comments.

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.