Python Numpy重塑

2024-10-01 15:42:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到了一个奇怪的错误,而试图重塑三维纽比阵列。在

数组(x)的形状是(6,10300),我想把它改成(63000)。在

我使用以下代码:

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

我收到的错误是:

^{pr2}$

但是,如果我把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

Tags: 代码列表outputlen错误np数组形状
1条回答
网友
1楼 · 发布于 2024-10-01 15:42:39

只有当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(鉴于编辑历史:在您的案例中发生了这样的情况):

^{pr2}$

然而,它似乎与变通方法一起工作,这也使得不小心键入错误的内容变得更加困难:

>>> 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.

相关问题 更多 >

    热门问题