numpy:`arange`s的数组 [英] Numpy: Array of `arange`s

查看:126
本文介绍了numpy:`arange`s的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法...

>>> x = np.array([0, 8, 10, 15, 50]).reshape((-1, 1)); ncols = 5

...然后将其变成...

...and turn it into...

array([[ 0,  1,  2,  3,  4],
       [ 8,  9, 10, 11, 12],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [50, 51, 52, 53, 54]])

我能够用np.apply_along_axis ...

>>> def myFunc(a, ncols):
        return np.arange(a, (a+ncols))

>>> np.apply_along_axis(myFunc, axis=1, arr=x)

并带有for循环...

>>> X = np.zeros((x.size,ncols))
>>> for a,b in izip(xrange(x.size),x):
        X[a] = myFunc(b, ncols)

但是它们太慢了.有没有更快的方法?

but they are too slow. Is there a faster way?

提前谢谢.

推荐答案

以下将完成此操作:

In [9]: x = np.array([0, 8, 10, 15, 50]).reshape((-1, 1))

In [10]: ncols = 5

In [11]: x + np.arange(ncols)
Out[11]: 
array([[ 0,  1,  2,  3,  4],
       [ 8,  9, 10, 11, 12],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [50, 51, 52, 53, 54]])

它将行向量添加到列向量,并依赖于广播完成其余的工作.

It adds a row vector to a column vector and relies on broadcasting to do the rest.

这应该和任何东西一样快:生成1000x1000矩阵大约需要1.6ms:

This should be as fast as anything: producing a 1000x1000 matrix takes ~1.6ms:

In [17]: %timeit np.arange(1000).reshape((-1, 1)) + np.arange(1000)
1000 loops, best of 3: 1.61 ms per loop

这篇关于numpy:`arange`s的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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