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.]]
您可以通过以下方式做到这一点:
np.array([a] * 5)
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]])
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]
])
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.