6

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.

2
  • To be able to answer, we really need a more detailed explanation of what exactly you're trying to do. Or perhaps a complete code example that works but is too slow. Commented Jan 25, 2013 at 7:38
  • @JanneKarila: Yes, generic is what i'm going for. This is just a simple example. In real life, the values in x and the number of columns could be anything. But given values in x and ncol, return array of aranges of shape (x.size,ncol). Commented Jan 25, 2013 at 7:38

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

1 Comment

Geez...Thanks, @NPE. One of these days, i'll get the hang of this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.