PythonNumpy重塑错误 [英] Python Numpy Reshape Error

查看:17
本文介绍了PythonNumpy重塑错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试重塑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

推荐答案

仅当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

或如果它是array(给定编辑历史:这就是您的情况):

>>> 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。在这种情况下,该值是从数组的长度和剩余维度推断出来的。

这篇关于PythonNumpy重塑错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆