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!
where(...). The expression(x[1:] > 5) & (x[0:-1] > 5)is a boolean array that you could probably use in place of thewhere(...)result, or, if you need integers, convert using the.astype(int)method:((x[1:] > 5) & (x[0:-1] > 5)).astype(int).len(x) - 1times. For a small array, it might not matter, but if in your actual codexcan be much larger, you could do something like:xgt5 = x > 5; result = xgt5[1:] & xgt5[:-1]