多个范围/np.arange [英] Multiple ranges / np.arange

查看:168
本文介绍了多个范围/np.arange的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个如下的端点数组:

I have two end-point arrays that look like this:

t1 = np.array([0,13,22,...,99994])
t2 = np.array([4,14,25,...,99998])

我正在寻找生成如下所示输出的最有效方法:

I am looking for the most efficient way to generate an output that looks like this:

np.array([0,1,2,3,4,13,14,22,23,24,25,...,99994,99995,99996,99997,99998])

做到这一点的一种方法是:

one way to do it is this:

np.array([i for a, b in zip(t1, t2) for i in range(a, b + 1)])

此解决方案很慢,我敢肯定,可以通过完全用Numpy中的某些功能完全替换zip和list理解组合来仍然对其进行极大地改进,只是我不知道该怎么做.你们能告诉我最有效的方法吗?

This solution is slow and I am certain that it can still be vastly improved by entirely replacing the zip and list comprehension combo with some functions entirely in Numpy, it is just that I don't know how. Can you guys show me the most efficient way to do it?

提前谢谢你们

生成这两个数组的代码:

Code to generate these two arrays:

import numpy as np

m =10000
Z = np.arange(0,10*m,10)

t1 = np.random.randint(5, size =m ) + Z
t2 =np.random.randint(5,size = m) + 5 + Z

推荐答案

这是使用numba的高效方法:

from numba import njit

@njit
def n_ranges_nb(t1, t2):
    a = np.arange(np.max(t2)+1)
    n = (t2 - t1).sum()
    out = np.zeros(n)
    l, l_old = 0, 0
    for i,j in zip(t1, t2):
        l += j-i
        out[l_old:l] = a[i:j]
        l_old = l
    return out

使用与上述相同的值进行检查:

Checking with the same values as above:

t1 = np.array([0,13,22])
t2 = np.array([4,14,25])

n_ranges_nb(t1, t2+1)
# array([ 0.,  1.,  2.,  3.,  4., 13., 14., 22., 23., 24., 25.])


让我们检查时间:


Lets check the timings:

d = 100
perfplot.show(
    setup=lambda n: np.cumsum(np.random.randint(0, 50, n)),

    kernels=[
        lambda x: np.array([i for a, b in zip(x,x+d) for i in range(a,b+1)]),
        lambda x: n_ranges_nb(x, x+d+1),
        lambda x: create_ranges(x, x+d+1) # (from the dupe)
    ],

    labels=['nested-list-comp', 'n_ranges_nb', 'create_ranges'],
    n_range=[2**k for k in range(0, 18)],
    xlabel='N'
)

这篇关于多个范围/np.arange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆