'How to expand a numpy vector n times into an 2d array with its own values

With numpy, say you have a vector like:

array([1, 2, 3])

How do you extend it n times with its own values? E.g.:

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


Solution 1:[1]

You can use numpy.tile:

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

b = np.tile(a, (N,1))

or numpy.vstack:

N = 3
b = np.vstack([a]*N)

output:

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

Solution 2:[2]

You can use numpy.repeat:

_REP_ = 3
arr = np.array([1, 2, 3])
res = np.repeat(a[None,:], _REP_, axis=0)
print(res)

# Explanation
# a[None, :] 
# or 
# a.reshape(1,-1)
# => array([[1, 2, 3]])

Output:

[[1 2 3]
 [1 2 3]
 [1 2 3]]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mozway
Solution 2 I'mahdi