Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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]

like image 407
stelios Avatar asked Mar 25 '14 12:03

stelios


People also ask

Is NumPy concatenate faster than append?

In general it is better/faster to iterate or append with lists, and apply the np. array (or concatenate) just once. appending to a list is fast; much faster than making a new array.

Can you concatenate NumPy arrays?

Joining Arrays Using Stack FunctionsWe can concatenate two 1-D arrays along the second axis which would result in putting them one over the other, ie. stacking. We pass a sequence of arrays that we want to join to the stack() method along with the axis.

How do I repeat an array in NumPy?

In Python, if you want to repeat the elements multiple times in the NumPy array then you can use the numpy. repeat() function. In Python, this method is available in the NumPy module and this function is used to return the numpy array of the repeated items along with axis such as 0 and 1.

Is appending to NumPy array faster than list?

array(a) . List append is faster than array append .


2 Answers

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

like image 50
Cory Kramer Avatar answered Sep 28 '22 13:09

Cory Kramer


You could use vstack:

numpy.vstack([X]*N) 

e.g.

>>> import numpy as np >>> X = np.array([1,2,3,4]) >>> N = 7 >>> np.vstack([X]*N) array([[1, 2, 3, 4],        [1, 2, 3, 4],        [1, 2, 3, 4],        [1, 2, 3, 4],        [1, 2, 3, 4],        [1, 2, 3, 4],        [1, 2, 3, 4],        [1, 2, 3, 4],        [1, 2, 3, 4]]) 
like image 23
atomh33ls Avatar answered Sep 28 '22 11:09

atomh33ls