【问题标题】:Finding the centroid of values between zeros in an 1-D array without iteration在没有迭代的情况下查找一维数组中零之间的值的质心
【发布时间】:2021-11-18 11:20:08
【问题描述】:

我目前正在尝试数据系列,例如:

a = np.array([0,0,0,8,13,12,5,0,0,05,6,8,14,0,0,0]) 

获取零之间的每个数字集合的质心以及它们在数组中的位置。在这里,职位对我来说更重要——我还没有找到解决这个问题的好方法。

【问题讨论】:

  • “零之间的每个数字集合”是什么意思?能举个例子吗?
  • 感谢您的回复。例如,这里的数字集合是 8,13,12,5。所以质心将位于数字 13 的位置。第二个数字集体 wuold 是 5、6、8、14,这里的质心将是 8。大约是 50% 之间的零之间的数字的累积值。希望我能解释得足够好
  • 请阅读stackoverflow.com/questions/70012889/…。这基本上是完全相同的问题,但在 2D 中(今天发布的类似其他问题)。

标签: python numpy centroid


【解决方案1】:

您可以执行以下操作:

  • 查找非零项的索引:

    arr = np.array([0,0,0,8,13,12,5,0,0,0,5,6,8,14,0,0,0])
    idx = np.flatnonzero(x!=0)
    >>> idx
    array([ 3,  4,  5,  6, 10, 11, 12, 13], dtype=int64)
    
  • 找到边界:

    starting_idx = idx[np.diff(idx, prepend=idx[0])!=1]
    ending_idx = idx[np.diff(idx, append=idx[-1])!=1]
    bounding_idx = np.transpose([starting_idx, ending_idx])
    >>> bounding_idx
    array([[ 3,  6], [10, 13]], dtype=int64)
    
  • 获取质心候选者的索引:

    c = np.mean(bounding_idx, axis=1)
    c1 = np.floor(c).astype(int)
    c2 = np.ceil(c).astype(int)
    candidate_idx = np.transpose([c1, c2])
    >>> candidate_idx
    array([[ 4,  5], [11, 12]])
    
  • 自己寻找候选人:

    candidates = arr[np.ravel(candidate_idx)].reshape(-1,2)
    >>> candidates
    array([[13, 12], [ 6,  8]])
    
  • 查找对应于质心的候选索引:

    centroid_idx = np.argmax(candidates, axis=1)
    >>> centroid_idx
    array([0, 1], dtype=int64)
    
  • 最后,获取质心及其索引:

    >>> candidates[np.arange(len(candidates)), centroid_idx]
    array([13,  8])
    >>> candidate_idx[np.arange(len(candidate_idx)), centroid_idx]
    array([ 4, 12])
    

【讨论】:

  • 哇,谢谢!这就是我需要的!
  • 不客气!如果它解决了您的问题,请不要忘记投票支持我的答案。
猜你喜欢
  • 1970-01-01
  • 2017-03-25
  • 2016-07-12
  • 1970-01-01
  • 2018-09-23
  • 2021-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多