Python Numpy重塑错误

4

当我尝试对3D numpy数组进行重新塑形时,遇到了一个奇怪的错误。

数组(x)的形状为(6,10,300),我想将其重塑为(6,3000)。

我使用以下代码:

reshapedArray = np.reshape(x, (x.shape[0], x.shape[1]*x.shape[2]))

我收到的错误是:
TypeError: only integer scalar arrays can be converted to a scalar index

然而,如果我将x转换为列表,它就可以工作:
x = x.tolist()
reshapedArray = np.reshape(x, (len(x), len(x[0])*len(x[0][0])))

您有任何想法为什么会出现这个问题吗?

提前感谢!

编辑:

这是我正在运行并导致错误的代码。

x = np.stack(dataframe.as_matrix(columns=['x']).ravel())

print("OUTPUT:")
print(type(x), x.dtype, x.shape)
print("----------")

x = np.reshape(x, (x.shape[0], x.shape[1]*x[2]))

OUTPUT:
<class 'numpy.ndarray'> float64 (6, 10, 300)
----------

TypeError: only integer scalar arrays can be converted to a scalar index

你能报告一下:type(x)x.dtype吗? - Divakar
3
我对上面的代码没有问题。你能否发布一个最小化示例,展示出这个错误? - Pierre de Buyl
@MSeifert 第一个传递3000,第二个<class 'int'>(和预期一样,但这使得错误非常奇怪,它必须与x内部的数据有关)。 - SirTobi
2
整个情况听起来好像你没有注意到你告诉我们的和你实际运行的之间存在一些重要的差异。 - user2357112
2
我可以通过使用有错别字的代码行来重现错误:np.reshape(x, (x.shape[0], x.shape[1]*x[2])) - Warren Weckesser
显示剩余19条评论
1个回答

1

只有当reshape的第二个参数中的一个元素不是整数时,才会出现异常,例如:

>>> x = np.ones((6, 10, 300))
>>> np.reshape(x, (np.array(x.shape[0], dtype=float), x.shape[1]*x.shape[2]))
TypeError: only integer scalar arrays can be converted to a scalar index

或者如果它是一个数组(根据编辑历史记录:这就是你的情况所发生的):
>>> np.reshape(x, (x.shape[0], x.shape[1]*x[2]))
#         forgot to access the shape------^^^^
TypeError: only integer scalar arrays can be converted to a scalar index

然而,使用这种解决方法似乎可以解决问题,同时也使得意外输错内容变得更加困难。
>>> np.reshape(x, (x.shape[0], -1))

如果你对于-1感到困惑,文档进行了解释:

一个形状维度可以是-1。在这种情况下,该值将从数组的长度和其余维度中推断出。


2
@SirTobi,我看到你接受了这个答案,但错误的来源仍然是神秘的。有没有可能你可以添加一个自包含的可运行示例,这样我们那些对问题感到好奇的人就可以尝试重现它? - Warren Weckesser
@WarrenWeckesser,我无法用不同的数据重现这个错误,有办法可以在这里上传我的h5文件吗? - SirTobi
我不知道你可以上传到哪里。同时,如果你在运行确切的代码行“reshapedArray = np.reshape(x, (x.shape[0], x.shape[1]*x.shape[2]))”之前立即输入“print(type(x), x.dtype, x.shape)”,你确定输出是“<class 'numpy.ndarray'> float64 (6, 10, 300)”吗? - Warren Weckesser
@WarrenWeckesser 是的,这是输出结果:输出结果: <class 'numpy.ndarray'> float64 (6, 10, 300) ---------- 我会提供更多细节的答案 - SirTobi
1
@SirTobi,你说你有一个DataFrame,将其存储为hdf5,然后在进行重塑之前加载。在这种情况下,只需创建一个仅包含1(或random.random(size))的数据框,保存它,加载它(就像之前一样),然后进行重塑。如果错误再次发生,请在问题中包含您所做的所有操作。 - MSeifert
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接