【问题标题】:Distance to next non-zero element in one-dimensional numpy array一维numpy数组中到下一个非零元素的距离
【发布时间】:2020-12-15 14:29:47
【问题描述】:

我有一个由 1 和 0 组成的一维 numpy 数组,如下所示:

[0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1]

对于数组的每个非零元素,我想计算到下一个非零元素的“距离”。也就是说,我想回答“下一个非零元素还有多远?”这个问题。所以上述数组的结果是:

[0, 0, 0, 1, 3, 0, 0, 6, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0]

这个有内置的 numpy 函数吗?如果没有,在 numpy 中实现这一点的最有效方法是什么?

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    这里有 2 个衬垫。如果您不想覆盖原始 a 替换为 copy()

    import numpy as np
    a = np.array([0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1])
    
    ix = np.where(a)[0]
    a[ix[:-1]] = np.diff(ix)
    
    print(a[:-1]) # --> array([0, 0, 0, 1, 3, 0, 0, 6, 0, 0, 0, 0, 0, 4, 0, 0, 0])
    

    【讨论】:

    • 输出的末尾有一个
    • 是的,但这是细微差别。你可以随时b=a[:-1]
    【解决方案2】:

    可能不是最佳答案。

    np.where 将按递增顺序为您提供非零索引的位置。通过对结果进行迭代,可以知道每个1的位置和后面的1的位置,可以自己轻松构建结果数组。如果 1 是稀疏的,这可能非常有效。

    让我看看我能不能想到一些更 numpy-ish 的东西。

    == 更新 ==

    啊,刚来找我

    # Find the ones in the array
    temp = np.where(x)[0]
    # find the difference between adjacent elements
    deltas = temp[1:] - temp[:-1]
    # Build the result based on these
    result = np.zeros_like(x)
    result[temp[:-1]] = deltas
    

    【讨论】:

      【解决方案3】:

      我们试试吧:

      import numpy as np
      
      arr = np.array([0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1])
      
      # create output
      res = np.zeros_like(arr)
      
      # select indices non-zero
      where, = np.where(arr)
      
      # assign the indices of the non-zero the diff
      res[where[:-1]] = np.diff(where)
      print(res)
      

      输出

      [0 0 0 1 3 0 0 6 0 0 0 0 0 4 0 0 0 0]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-16
        • 1970-01-01
        • 1970-01-01
        • 2018-01-27
        • 1970-01-01
        • 1970-01-01
        • 2023-03-14
        • 2020-07-10
        相关资源
        最近更新 更多