简体   繁体   English

检查numpy数组的真实性,但检查2个值

[英]checking for truthiness on a numpy array but for 2 values

I have a numpy array such as 我有一个numpy数组,例如

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 假设x是一个“时间序列”,我正在2个条件下测试真实性,如果x t大于5并且x t-1同时大于5

is there a more pythonic way to write this test: 有没有更多的pythonic方式来编写此测试:

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. 我觉得调用x[1:]x[0:-1]以获得滞后值有点奇怪。

any better way? 还有更好的方法吗?

thanks! 谢谢!

I wouldn't call your expression "weird"; 我不会把你的表情叫做“怪异”; using shifted slices like that is pretty common in numpy code. 在numpy代码中使用这样的移位切片非常普遍。 There is some inefficiency, because you are repeating the same comparison len(x) - 1 times. 由于您要重复相同的比较len(x) - 1次,因此效率低下。 For a small array, it might not matter, but if in your actual code x can be much larger, you could do something like: 对于较小的数组,可能没有关系,但是如果在您的实际代码中x可以大得多,则可以执行以下操作:

xgt5 = x > 5
result = xgt5[1:] & xgt5[:-1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM