繁体   English   中英

创建具有连续整数但忽略特定数字的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,]

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

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)
    ])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM