部分原因是针对Nelson rules和Western Electric rules检查数据系列。
例如(尼尔森规则中的规则2):检查一行中的九个(或更多)点是否位于均值的同一侧。
现在我可以通过遍历数组来简单地实现检查这样的规则。
答案 0 :(得分:2)
import numpy as np
x = np.random.rand(100)
f = np.sign(x - x.mean())
c = np.cumsum(f)
d = c[9:] - c[:-9]
print np.max(d), np.min(d)
如果np.max(d)== 9或np.min(d)== -9则连续九个(或更多)点位于均值的同一侧。
或者您可以使用以下代码计算每一行的长度:
np.diff(np.where(np.diff(np.r_[-2,f,-2]))[0])
答案 1 :(得分:1)
给定data
和最小length
,您可以检查数组是否
np.diff(np.cumsum(np.sign(data - np.mean(data))), length)
包含零。
答案 2 :(得分:1)
另一种可能性:使用关联或卷积
>>> a = np.random.randn(50)
>>> b = (a - a.mean()) > 0
>>> b.astype(int)
array([0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1,
1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0,
1, 1, 1, 1])
>>> c = np.correlate(b, np.ones(3), mode='valid')
>>> c
array([ 2., 2., 1., 1., 1., 1., 0., 0., 1., 2., 3., 2., 2.,
1., 1., 0., 0., 1., 2., 3., 3., 3., 3., 3., 2., 2.,
2., 2., 2., 1., 1., 1., 1., 2., 1., 2., 2., 2., 1.,
0., 0., 1., 2., 2., 2., 2., 3., 3.])
>>> c.max() == 3
True
>>> c.min() == 0
True
它会比HYRY cumsum版本慢。
除此之外:statsmodels中有一个运行测试用于测试类似的运行
答案 3 :(得分:1)
正如我在评论中提到的,你可能想尝试使用一些大步技巧。
首先,让我们创建一个异常大小的数组:我们可以将其设为np.int8
以节省一些空间
anomalies = x - x.mean()
signs = np.sign(anomalies).astype(np.int8)
现在大踏步前进。如果您想考虑N
个连续点,您将使用
from np.lib.stride_tricks import as_strided
strided = as_strided(signs,
strides=(signs.itemsize,signs.itemsize),
shape=(signs.shape,N))
这为我们提供了(x.size, N)
rollin数组:第一行是x[0:N]
,第二行是x[1:N+1]
...当然,最后N-1
行将毫无意义,所以从现在起我们将使用
strided = strided[:-N+1]
让我们沿着行总和
consecutives = strided.sum(axis=-1)
这为我们提供了(x.size-N+1)
和-N
之间的+N
大小的数组:我们只需找到绝对值N
的位置:
(indices,) = np.nonzero(consecutives == N)
indices
是数组i
的索引x
的数组,其值x[i:i+N]
位于均值的同一侧...
x=np.random.rand(10)
和N=3
>>> x = array([ 0.57016436, 0.79360943, 0.89535982, 0.83632245, 0.31046202,
0.91398363, 0.62358298, 0.72148491, 0.99311681, 0.94852957])
>>> signs = np.sign(x-x.mean()).astype(np.int8)
array([-1, 1, 1, 1, -1, 1, -1, -1, 1, 1], dtype=int8)
>>> strided = as_strided(signs,strides=(1,1),shape=(signs.size,3))
array([[ -1, 1, 1],
[ 1, 1, 1],
[ 1, 1, -1],
[ 1, -1, 1],
[ -1, 1, -1],
[ 1, -1, -1],
[ -1, -1, 1],
[ -1, 1, 1],
[ 1, 1, -106],
[ 1, -106, -44]], dtype=int8)
>>> consecutive=strided[:-N+1].sum(axis=-1)
array([ 1, 3, 1, 1, -1, -1, -1, 1])
>>> np.nonzero(np.abs(consecutive)==N)
(array([1]),)