Repeat 1d array into 2d numpy matrix

Issue

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

Solution

Using NumPy append in loop:

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)

Answered By – Gerald Negvesky

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published