【问题标题】:How to insert a matrix into an numpy array?如何将矩阵插入到 numpy 数组中?
【发布时间】:2023-01-11 12:33:46
【问题描述】:

我有一些通过命令生成的weights

weights = np.random.rand(9+1, 8)                                                  
for i in range(8): # 7 to 8
    weights[9][i] = random.uniform(.5,1.5)

然后,我尝试将它插入到以下lattice 的元素中:

lattice = np.zeros((2,10,5))
lattice[0][0][0] = weights
print(lattice)

这导致错误:

ValueError: setting an array element with a sequence.

我的问题是: 如何将weights插入lattice

我知道问题是格子中充满了 float 值,所以它不能接受矩阵。

我有兴趣找到一种方法来生成具有正确数量元素的格子,以便我可以插入我的矩阵。一个例子会很有帮助。

我读过几篇关于 stackoverflow 的文章,包括:

how to append a numpy matrix into an empty numpy array

ValueError: setting an array element with a sequence

Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence?

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    据推测,在您完成填充格子之前,您不需要它实际上是一个 numpy 数组。因此,您可以做的就是使用嵌套列表,然后在整个列表上调用 numpy 数组。你可以这样做:

    lattice = [[[None for _ in range(5)] for _ in range(10)] for _ in range(2)]
    

    然后使用:

    lattice[0][0][0] = weights
    

    填写完所有元素后,请调用:

    lattice = np.array(lattice)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      • 1970-01-01
      • 2013-11-26
      • 2021-10-25
      • 1970-01-01
      • 2012-05-28
      相关资源
      最近更新 更多