【问题标题】:Finding indices of runs of integers in an array查找数组中整数运行的索引
【发布时间】:2021-09-08 14:38:39
【问题描述】:

我有一个以整数作为条目的 numpy 数组。我需要找到与数组中整数运行相对应的索引。例如,如果我的数组是a = [1, 2, 3, 6, 7, 8],那么我想要的索引是[[0, 1, 2], [3, 4, 5]]。我尝试了以下使用循环的代码。

import numpy as np

idx = np.array([0, 1, 2, 3, 8, 9, 10, 11, 12, 2, 3, 4, 5, 6, 55, 56, 89, 90, 91, 92])
idx_cpy = idx

indices = []

while len(idx) > 0:
    sorted_idx = np.arange(idx[0], idx.max()+1)[:len(idx)]
    bool_equal = np.equal(sorted_idx, idx)
    true_idx = np.argwhere(bool_equal == True)[:, 0]
    try:
        indices.append(np.array(indices[-1]).max() + 1 + true_idx)
    except IndexError:
        indices.append(true_idx)
    idx = idx[true_idx.max()+1:]


"""
indices = 
[array([0, 1, 2, 3], dtype=int64), 
array([4, 5, 6, 7, 8], dtype=int64), 
array([ 9, 10, 11, 12, 13], dtype=int64), 
array([14, 15], dtype=int64), 
array([16, 17, 18, 19], dtype=int64)]
"""

虽然这可以按预期工作,但我的实际代码中的变量idx 的长度很大,这需要很长时间才能完成。有没有一种矢量化的方式来做到这一点?谢谢。

【问题讨论】:

  • 我不太明白你想对数组做什么。你能再给我一个你想要做的数组的例子吗?
  • @MushfiratMohaimin,我需要数组中整数连续运行的索引。列表indices 中的第一个条目对应于实际数组idx 中具有连续整数的那些索引。这清楚还是我让情况变得更糟了?

标签: python arrays python-3.x numpy


【解决方案1】:

您可以使用 np.diff 找到“转折点”并检查它与 1 的不同之处。为了包含端点,我们将 prependappend 传递给它,这样这些地方的差异就不是 1他们也被计算在内。然后使用np.arange 的列表理解给出最终结果:

>>> turnings, = np.where(np.diff(a, prepend=a[0], append=a[-1]) != 1)
>>> turnings

array([ 0,  4,  9, 14, 16, 20], dtype=int64)

>>> result = [np.arange(pre, nex) for pre, nex in zip(turnings, turnings[1:])]
>>> result

[array([0, 1, 2, 3], dtype=int64),
 array([4, 5, 6, 7, 8], dtype=int64),
 array([ 9, 10, 11, 12, 13], dtype=int64),
 array([14, 15], dtype=int64),
 array([16, 17, 18, 19], dtype=int64)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 2020-02-27
    • 2014-05-08
    • 1970-01-01
    • 2016-06-09
    相关资源
    最近更新 更多