Python: Concatenate (or clone) a numpy array N times

stelios picture stelios · Mar 25, 2014 · Viewed 44.7k times · Source

I want to create an MxN numpy array by cloning a Mx1 ndarray N times. Is there an efficient pythonic way to do that instead of looping?

Btw the following way doesn't work for me (X is my Mx1 array) :

   numpy.concatenate((X, numpy.tile(X,N)))

since it created a [M*N,1] array instead of [M,N]

Answer

Cory Kramer picture Cory Kramer · Mar 25, 2014

You are close, you want to use np.tile, but like this:

a = np.array([0,1,2])
np.tile(a,(3,1))

Result:

array([[0, 1, 2],
   [0, 1, 2],
   [0, 1, 2]])

If you call np.tile(a,3) you will get concatenate behavior like you were seeing

array([0, 1, 2, 0, 1, 2, 0, 1, 2])

http://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html