Python Numpy reshape 错误

标签 python numpy reshape

<分区>

我在尝试 reshape 3D numpy 数组时遇到了一个奇怪的错误。

数组 (x) 的形状为 (6, 10, 300),我想将其 reshape 为 (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

或者如果它是一个数组(考虑到编辑历史:这就是你的情况):

>>> 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,文档会对其进行解释:

One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

关于Python Numpy reshape 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45927263/

相关文章:

python - 如何使用 pandas 数据框中该行中的字段查找和修改特定行?

python线性回归实现

pytorch - reshape() 与 contigious().view() 相同吗?

r - 如何在ggplot2中将热图和散点图一个放在另一个之上

r - 将列堆叠为R中的1列

python - 带有OpenCV 3的OpenNI2

python - 如何停止用户输入和 pygame 显示之间的滞后

python - 来自第一维的 numpy 广播

python - 了解 Keras EarlyStopping 的行为

python - 当数据不是周期性的时,如何绘制基于堆叠的条形图