【问题标题】:Appending to the rows and columns to Multi dimensional Arrays Numpy Python将行和列附加到多维数组 Numpy Python
【发布时间】:2021-08-21 20:00:08
【问题描述】:

我正在尝试追加以创建一个多维数组,其中每行输入 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))

预期输出:

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

【问题讨论】:

  • Array.shape 是 (1,0)。您无法通过分配新索引来改变它。该代码看起来像是 Python 列表代码和 MATLAB 之间的交叉。您需要花更多时间阅读numpy 介绍。不要假设 numpy 数组的工作原理。

标签: python arrays python-3.x numpy multidimensional-array


【解决方案1】:

不要这样做。稍后尝试使用np.append. If you must do something like this, use a listand then convert the resulting list to anumpy.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 作为结尾。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 2021-08-21
    • 2020-07-06
    • 2022-10-15
    • 2017-08-18
    • 2021-02-21
    • 2023-03-11
    相关资源
    最近更新 更多