【问题标题】:Python Numpy Reshape Error [closed]Python Numpy重塑错误[关闭]
【发布时间】:2018-02-06 05:04:09
【问题描述】:

我在尝试重塑 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
  • type = dtype = float64
  • 我对上面的代码没有任何问题。你能发一个minimal example来显示这个错误吗?
  • 整个情况听起来好像在您告诉我们的内容与您实际运行的内容之间存在一些您没有注意到的关键差异。
  • 我可以通过使用有错字的行来重现错误:np.reshape(x, (x.shape[0], x.shape[1]*x[2]))

标签: python numpy reshape


【解决方案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

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

【讨论】:

  • 非常感谢您的解决方法!即使我输入 int(x.shape[1]*x.shape[2]) 它也不起作用并显示一个新错误:TypeError: only length-1 arrays can be convert to Python scalars
  • @SirTobi,我看到你接受了这个答案,但错误的来源仍然很神秘。您是否有机会添加一个独立的、可运行的示例,以便我们这些对这个问题感到好奇的人可以尝试重现它?
  • @SirTobi 什么......这变得非常神秘。 x.shape[1]*x.shape[2] 怎么可能是 NumPy 数组。
  • @WarrenWeckesser 是的,所以我正在从从 h5 文件加载到的 pandas 数据框中检索数据,我尝试创建一个可运行的示例。
  • @SirTobi 您说您有一个 DataFrame 存储为 hdf5,然后在进行重塑之前加载。在这种情况下,只需创建一个只包含一个(或random.random(size)s)的数据框,保存它,加载它(就像你之前所做的那样)并进行重塑。如果错误再次发生,请包括您在问题中所做的所有事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-31
  • 2018-10-13
  • 2017-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多