Is there a 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 it 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.
The following will do it:
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With