Steven G
Steven G

Reputation: 17122

checking for truthiness on a numpy array but for 2 values

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!

Upvotes: 0

Views: 109

Answers (1)

Warren Weckesser
Warren Weckesser

Reputation: 114781

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]

Upvotes: 1

Related Questions