[Numpy-discussion] is there a better way to do this array repeat?

Robert Kern robert.kern at gmail.com
Sun Aug 16 20:07:23 EDT 2009


On Sun, Aug 16, 2009 at 19:01, Chris Colbert<sccolbert at gmail.com> wrote:
> I don't think np.repeat will do what I want because the order needs to
> be preserved.

"Order"?

> I have a 1x3 array that I want to repeat n times and form an nx3 array
> where each row is a copy of the original array.
>
> So far I have this:
>
>>>> import numpy as np
>>>> a = np.arange(3)
>>>> b = np.asarray([a]*10)
>>>> b
> array([[0, 1, 2],
>       [0, 1, 2],
>       [0, 1, 2],
>       [0, 1, 2],
>       [0, 1, 2],
>       [0, 1, 2],
>       [0, 1, 2],
>       [0, 1, 2],
>       [0, 1, 2],
>       [0, 1, 2]])
>>>> b.shape
> (10, 3)

In [5]: a = arange(3)

In [6]: repeat(a.reshape([1, -1]), 10, axis=0)
Out[6]:
array([[0, 1, 2],
       [0, 1, 2],
       [0, 1, 2],
       [0, 1, 2],
       [0, 1, 2],
       [0, 1, 2],
       [0, 1, 2],
       [0, 1, 2],
       [0, 1, 2],
       [0, 1, 2]])


-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco



More information about the NumPy-Discussion mailing list