I have a numpy array:
import numpy as np
A = np.array([1,2])
I want to make n-copies of both the elements in a 2-D numpy array, for example
B=[[1,1,1,1],[2,2,2,2]] # 4 copies of each element of A into a separate array
How can I do it?
Use np.repeat and then reshape -
np.repeat(A,4).reshape(-1,4)
That reshape(-1,4) basically keeps 4 number of columns and the -1 specifies it to compute the number of rows based on the total size of the array to be reshaped. Thus, for the given sample since np.repeat(A,4).size is 8, it assigns 8/4 = 2 as the number of rows. So, it reshapes np.repeat(A,4) into a 2D array of shape (2,4).
Or use np.repeat after extending A to 2D with None/np.newaxis -
np.repeat(A[:,None],4,axis=1)
Or use np.tile on extended version -
np.tile(A[:,None],4)
You could multiply it with another array containing 1s:
>>> import numpy as np
>>> A=np.array([1,2])
>>> A[:, np.newaxis] * np.ones(4, int)
array([[1, 1, 1, 1],
[2, 2, 2, 2]])
or if a read-only copy is sufficient you need you can also use broadcast_to (very, very fast operation):
>>> np.broadcast_to(A[:, None], [A.shape[0], 4])
array([[1, 1, 1, 1],
[2, 2, 2, 2]])