Numpy: Array `arange`s

Is there any way to take ...

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

I was able to do this with np.apply_along_axis ...

 >>> def myFunc(a, ncols): return np.arange(a, (a+ncols)) >>> np.apply_along_axis(myFunc, axis=1, arr=x) 

and with for loops ...

 >>> 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?

Thanks in advance.

+6
source share
1 answer

This will do the following:

 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.

It should be as fast as everything: creating a 1000x1000 matrix takes ~ 1.6 ms:

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

All Articles