创建具有连续整数但忽略特定数字的numpy数组的最快方法

Fastest way to create a numpy array with consecutive integer but ignore specific number

我需要生成一个用连续数字填充但忽略特定数字的 numpy 数组。

例如,我需要一个介于 0 到 5 之间的 numpy 数组,但忽略 3。结果将是 [0,1,2,4,5,]

当我需要的数组很大时,我当前的解决方案非常慢。这是我的测试代码,它在我的 i7-6770 机器上花费了 2m34s Python 3.6.5.

import numpy as np

length = 150000

for _ in range(10000):
    skip = np.random.randint(length)
    indexing = np.asarray([i for i in range(length) if i != skip])

所以,我想知道有没有更好的。谢谢

不是忽略数字,而是将数组分成两个范围,留下您忽略的数字。然后使用 np.arange 制作数组并连接它们。

def range_with_ignore(start, stop, ignore):
    return np.concatenate([
        np.arange(start, ignore),
        np.arange(ignore + 1, stop)
    ])