I am trying to append to create a multi dimensional array where it inputs 4 random numbers per row. The code below does not work. How would I be able to fix it?
import numpy as np
import random
Array = np.array([[]])
for i in range(3):
for k in range(4):
Array[i][k]= np.append(Array[i][k], random.randint(0,9))
Expected Output:
[[1,3,4,8],
[2,3,6,4],
[7,4,1,5],
[8,3,1,1]]
Don't do this . It is highly inefficient to try to create an array like this incrementally using np.append. If you must do something like this, use a
np.append. If you must do something like this, use a
list and then convert the resulting list to a
numpy.ndarray` later.
However, in this case, you simply want:
>>> import numpy as np
>>> np.random.randint(0, 10, (3,4))
array([[0, 3, 7, 4],
[6, 4, 2, 2],
[4, 4, 0, 6]])
Or perhaps:
>>> np.random.randint(0, 10, (4,4))
array([[8, 8, 2, 7],
[3, 7, 2, 1],
[5, 5, 5, 5],
[6, 2, 7, 9]])
Note, np.random.randint
has an exclusive end, so if you want to draw from numbers [0, 9] you need to use 9+1
as the end.
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.