求numpy中最小跳零交叉

2024-04-20 03:38:13 发布

您现在位置:Python中文网/ 问答频道 /正文

对于数据分析任务,我希望在numpy数组中找到零交叉点,它来自于一个先是sobel类内核的卷积,然后是一个墨西哥帽内核。零交叉允许我检测数据中的边缘。在

不幸的是,数据有点嘈杂,我只想在下面的例子中找到最小跳跃大小的零交叉点20

import numpy as np
arr = np.array([12, 15, 9, 8, -1, 1, -12, -10, 10])

应该会导致

^{pr2}$

或者

>>>array([3, 7])

其中3-1的索引,就在第一个跳转的中间之前,7是{}的索引

我已尝试对以下代码进行修改(源代码:Efficiently detect sign-changes in python

zero_crossings = np.where(np.diff(np.sign(np.trunc(arr/10))))[0]

它正确地忽略了小跳跃,但将零交叉放在[1,5,7]

做这件事的有效方法是什么?在

最小跳跃的定义并不严格,但结果应该符合我的问题。在

编辑:澄清

arr = np.array([12, 15, 9, 8, -1, 1, -12, -10, 10])
arr_floored = np.trunc(arr/10)
>>>>np.array([10, 10, 0, 0, 0, 0, -10, -10, 10])
sgn = np.sign(arr_floored)
>>>>array([ 1,  1,  0,  0,  0,  0, -1, -1,  1])
dsgn = np.diff(sgn)
>>>>array([ 0, -1,  0,  0,  0, -1,  0,  2])
np.where(dsgn)
>>>>(array([1, 5, 7], dtype=int64),)

其他边缘情况:

arr = [10,9,8,7,6,5,4,3,2,1,0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]

应该会导致

>>> np.array([10])

同时也注意到了:这个问题可能是不适定的(在数学意义上)。今天晚些时候我会澄清。在


Tags: 数据numpynpdiffwherearray内核交叉
2条回答

这里有一个解决方案,它给出了交叉点的中点,其中包含一个噪声阈值,用于过滤在多个数据点上应用的零附近的潜在多个波动。它给出了您提供的两个示例的正确答案。 不过,我做了几个假设:

  • 您没有精确地定义要考虑的数据点的范围来确定交叉点的中点,但我使用了您的示例代码作为基础-它检测ABS(start | end) >= 10的交叉点,因此我使用了这个条件存在的最小值范围。
    注意:这不会检测到从+15到-6的转换。
    编辑:实际上,它并不总是最小范围,但代码应该足以让您开始并根据需要进行调整。在
  • 我假设也可以使用pandas(跟踪感兴趣的数据点的索引)。如果必要的话,你可以避开熊猫。在

import numpy as np import pandas as pd arr = np.array([12, 15, 9, 8, -1, 1, -12, -10, 10]) sgn = pd.Series(np.sign(np.trunc(arr/10))) trailingEdge = sgn[sgn!=0].diff() edgeIndex = np.array(trailingEdge[trailingEdge!=0].index) edgeIndex[:-1] + np.diff(edgeIndex) / 2

给出:

array([3., 7.])

以及

arr = [10,9,8,7,6,5,4,3,2,1,0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]

给出:

{cd5}

基本情况

我想你想

import numpy as np
x = np.array([10, -50, -30, 50, 10, 3, -200, -12, 123])
indices = np.where(np.logical_and(np.abs(np.diff(x)) >= 20, np.diff(np.sign(x)) != 0))[0]

读作:索引,其中((x的绝对差)大于或等于20)和(符号翻转)

它回来了

^{pr2}$

周期信号

通常的numpy函数不包括这种情况。我建议在最后通过pad函数添加第一个元素:

import numpy as np
x = np.array([10, 5, 0, -5, -10])
x = np.pad(x, (0, 1), 'wrap')
indices = np.where(np.logical_and(np.abs(np.diff(x)) >= 20, np.diff(np.sign(x)) != 0))[0]

相关问题 更多 >