如何在numpy数组中找到从一个元素到下一个元素的状态转换? [英] How to find state transitions in a numpy array, from one element to the next?

查看:50
本文介绍了如何在numpy数组中找到从一个元素到下一个元素的状态转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确定数据集中的状态转换.一个示例是:"sin(x)低于哪个索引?"

I would like to identify state transitions in a data set. An example is: "At which index does the sin(x) fall below 0.5?"

我唯一能想到的就是这样:

The only way I could think of is like this:

a = np.arange(0,10,.01)
b= np.sin(a)
c = np.roll(b,1)
c[:1] = 0
print(a[(.5 > b) & (.5< c)])
[2.62 8.91]

我可以在没有附加数组c的情况下执行此操作吗?如何检测"sin(x)在哪个索引下低于0.5并停留在7个样本的位置?"的情况?我需要另外7个数组吗?

Can I do that without an additional array c? How can I detect cases like "At which index does sin(x) fall below 0.5 and stay there for 7 samples?" Would i need 7 additional arrays?

推荐答案

对于7个步骤,您只需构建一个中间数组即可:

For 7 steps, you can just build an intermediate array:

mask = (b < 0.5)
window = 7

# count the number of times the value is below thresh in the window
below_thresh = np.sum([mask[i:len(mask)-window+i] for i in range(window)], axis=0)

mask1 = below_thresh == window

a[window + 1:][mask1[1:] & (~mask1[:-1])]
# out 
# array([2.62, 8.91])

要获得更多步骤,可以使用 as_strided 更快地构建 below_thresh .

For higher number of steps, you can build the below_thresh faster with as_strided.

这篇关于如何在numpy数组中找到从一个元素到下一个元素的状态转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆