【发布时间】: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