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]
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.
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.
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.
array(a) . List append is faster than array append .
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
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]])
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