【问题标题】:Averaging indexes of peaks if they are close in Python如果它们在 Python 中接近,则平均峰值索引
【发布时间】:2015-03-08 19:31:07
【问题描述】:

这可能是一个简单的问题,但我还没有想出解决方案。 假设我有一个数组np.array([0,1,0,1,0,0,0,1,0,1,0,0,1]),其峰值位于索引[1,3,7,9,12]。如果在本例中将峰值之间的阈值距离设置为大于2,如何将索引替换为[2,8,12],即对距离较近的索引进行平均?

请注意,数组的二进制值只是为了说明,峰值可以是任何实数。

【问题讨论】:

  • 使用直方图,也许?
  • 假设您在 [1, 3, 5] 处有峰值。你想要[3](三个峰值的平均值)吗?还是[2,5]?还是 [1,4]?
  • 抱歉遗漏,我希望它是 3。可能不会有太多靠近的峰,为了简单起见,现在应该不考虑峰的相对高度来选择中间的峰。

标签: python arrays sorting replace average


【解决方案1】:

你可以使用Raymond Hettinger's cluster function:

from __future__ import division

def cluster(data, maxgap):
    """Arrange data into groups where successive elements
       differ by no more than *maxgap*

        >>> cluster([1, 6, 9, 100, 102, 105, 109, 134, 139], maxgap=10)
        [[1, 6, 9], [100, 102, 105, 109], [134, 139]]

        >>> cluster([1, 6, 9, 99, 100, 102, 105, 134, 139, 141], maxgap=10)
        [[1, 6, 9], [99, 100, 102, 105], [134, 139, 141]]
    """
    data.sort()
    groups = [[data[0]]]
    for item in data[1:]:
        val = abs(item - groups[-1][-1])
        if val <= maxgap:
            groups[-1].append(item)
        else:
            groups.append([item])
    return groups

peaks = [1,3,7,9,12]
print([sum(arr)/len(arr) for arr in cluster(peaks, maxgap=2)])

产量

[2.0, 8.0, 12.0]

【讨论】:

    猜你喜欢
    • 2020-04-10
    • 2021-02-22
    • 1970-01-01
    • 2019-01-13
    • 2020-11-11
    • 1970-01-01
    • 2021-05-06
    • 2019-03-07
    • 2020-02-04
    相关资源
    最近更新 更多