Numpy:有没有办法使用 np.argmax 来搜索连续值?



有没有办法在 Numpy 数组中搜索连续值并返回它们的索引?

例如,如果我们在数组上使用 argmax 来查找单个元素的第一个实例:

import numpy as np
a = np.array((0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1))
print(np.argmax(a == 1))

我们得到的结果:

3

有没有办法在同一个数组中搜索一对的第一个实例? 例如,我想获取以下代码的值6

import numpy as np
a = np.array((0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1))
print(np.argmax(a == [1, 1]))

但相反,它返回:

0

对于少量连续搜索模式,我们可以简单地切片并查找所有匹配项,最后使用我们最喜欢的argmax

因此,对于2连续搜索模式,它将是 -

In [6]: ((a[:-1]==1) & (a[1:]==1)).argmax()
Out[6]: 6

一些解释

这一切都与切片有关,因为我们得到了两个单偏移的数组切片。一个偏移量是因为连续搜索的窗口长度2。因此,对于搜索窗口长度为3,我们需要考虑双偏移数组切片等。现在,回到我们简单的两个连续窗口案例,我们有单偏移切片。我们将这些与1进行比较,这给了我们匹配的布尔数组。然后是AND-ing,这样整个窗口都被覆盖了。终于跳上我们的argmax,开始第一个岛屿

步骤的细分应该有助于进一步澄清给定的样本 -

In [24]: a
Out[24]: array([0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1])
In [25]: a[:-1]
Out[25]: array([0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1])
In [26]: a[:-1]==1
Out[26]: 
array([False, False, False,  True, False, False,  True,  True, False,
True,  True])
In [27]: a[1:]==1
Out[27]: 
array([False, False,  True, False, False,  True,  True, False,  True,
True,  True])
In [28]: (a[:-1]==1) & (a[1:]==1)
Out[28]: 
array([False, False, False, False, False, False,  True, False, False,
True,  True])
In [29]: ((a[:-1]==1) & (a[1:]==1)).argmax()
Out[29]: 6

连续出现次数更多

对于更多的缺点,我们可以求助于更内置的东西并使用np.convolve,就像这样 -

In [20]: W = 2 # window-length
In [21]: np.convolve(a,[1]*W,'same').argmax()-W//2
Out[21]: 6
In [22]: W = 3
In [23]: np.convolve(a,[1]*W,'same').argmax()-W//2
Out[23]: 9

最新更新