簡體   English   中英

將行和列附加到多維 Arrays Numpy Python

[英]Appending to the rows and columns to Multi dimensional Arrays Numpy Python

我正在嘗試 append 創建一個多維數組,其中每行輸入 4 個隨機數。 下面的代碼不起作用。 我將如何解決它?

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))

預期 Output:

[[1,3,4,8],
 [2,3,6,4],
 [7,4,1,5],
 [8,3,1,1]]

不要這樣做 嘗試使用np.append. If you must do something like this, use a逐步創建這樣的數組是非常低效的。 np.append. If you must do something like this, use a列表and then convert the resulting list to a numpy.ndarray`。

但是,在這種情況下,您只需要:

>>> import numpy as np
>>> np.random.randint(0, 10, (3,4))
array([[0, 3, 7, 4],
       [6, 4, 2, 2],
       [4, 4, 0, 6]])

也許:

>>> np.random.randint(0, 10, (4,4))
array([[8, 8, 2, 7],
       [3, 7, 2, 1],
       [5, 5, 5, 5],
       [6, 2, 7, 9]])

注意, np.random.randint有一個排他的結尾,所以如果你想從數字 [0, 9] 中抽取,你需要使用9+1作為結尾。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM