4

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?

3 Answers 3

3

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)
Sign up to request clarification or add additional context in comments.

Comments

1

You can use matrix multiplication with a (properly shaped) array of 1s and then transpose the final array.

import numpy as np

A = np.array([1, 2])

n = 4
B = np.ones((n, 1))
out = (A*B).T

You could also use np.vstack and then transpose the array.

out = np.vstack((A,)*n).T

Comments

1

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]])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.