简体   繁体   English

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

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

I need to generate a numpy array fill with consecutive numbers but ignore a specific number. 我需要生成一个用连续数字填充的numpy数组,但忽略特定的数字。

For example, I need a numpy array between 0 to 5 but ignore 3. The result will be [0,1,2,4,5,] . 例如,我需要一个0到5之间的numpy数组,但忽略3。结果将是[0,1,2,4,5,]

My current solution is very slow when the array size I need is large. 当我需要的数组大小很大时,我当前的解决方案非常慢。 Here is my testing code and it took 2m34s on my i7-6770 machine with Python 3.6.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])

Hence, I would like to know if there's better one. 因此,我想知道是否有更好的选择。 Thanks 谢谢

Instead of ignoring a number, split your array into two ranges, leaving the number you're ignoring out. 不要忽略数字,而是将数组分成两个范围,而忽略要忽略的数字。 Then use np.arange to make the arrays and concatenate them. 然后使用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