Home > Back-end >  Repeat 1d array into 2d numpy matrix
Repeat 1d array into 2d numpy matrix

Time:06-11

For a 1-d numpy array: [0, 0, 0, 0, 0, 0, 0, 0, 0, 1], I want to repeat it by having say 5 such arrays stacked along axis=1. Desired output:

[[0., 0., 0., 0., 0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 1.]]

CodePudding user response:

You can do this by:

np.array([a] * 5)

CodePudding user response:

You can do exactly that using np.repeat

np.repeat([[0, 0, 0, 0, 0, 0, 0, 0, 0, 1]], 5, axis=0)

Produces:

array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]])

CodePudding user response:

You can achieve this with np.tile:

np.tile([0, 0, 0, 0, 0, 0, 0, 0, 0, 1], (5, 1))

Output:

   array([
   [0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
   [0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
   [0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
   [0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
   [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
   ])

CodePudding user response:

Try this

import numpy as np

output = lst = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 1])

for i in range(5 - 1): #Put your desired number here instead of the 5
    output = np.append(output, lst)

output = output.reshape(-1, len(lst)) #Reshaping

print(output)


  • Related