如何使用python保存数组中的值

时间:2018-10-17 16:08:47

标签: python arrays python-3.x numpy

我想使用numpy将值保存到数组中。一切工作正常,但是当我尝试将值保存到数组中时出现错误。到目前为止,这是我所做的:

import numpy as np
batchSize = 2
numClasses = 2
maxSeqLength = 10 #Maximum length of sentence

labels = []
arr = np.zeros([batchSize, maxSeqLength])

for i in range(batchSize):
    num = randint(1,17)
    labels.append([1,0])
    # print(num)
    print(labels)
    print(ids[num-1:num])
    arr[i]=ids[num-1:num]

当我打印ids矩阵时,我会得到这些值

[[1, 0]]
[[   nan 11501.   420.  5842.    nan  4245.    nan     0.     0.     0.
      0.     0.     0.     0.     0.     0.     0.     0.     0.     0.
      0.     0.     0.     0.     0.     0.     0.     0.     0.     0.]]
[[1, 0], [1, 0]]
[[   nan    nan  7624.  3936. 11501.  8064.  5842.    nan    nan  1087.
     37. 11516.    nan 10936.    nan 12111.     0.     0.     0.     0.
      0.     0.     0.     0.     0.     0.     0.     0.     0.     0.]]

这是保存arr数组时遇到的错误

could not broadcast input array from shape (30) into shape (10)

1 个答案:

答案 0 :(得分:2)

错误非常明显,您正在尝试将30个元素的数组插入10个元素的数组中。这意味着arr[i]具有maxSeqLength=10,而ids[num-1:num]具有不同的length=30

您可以通过在生成maxSeqLength=30矩阵之前设置np.zero来解决此问题。