2017-08-28 93 views
-1

我在尝试重塑3D numpy数组时遇到了一个奇怪的错误。Python Numpy Reshape Error

数组(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 
+0

你可以报告:'type(x)'和'x.dtype'? – Divakar

+0

type = dtype = float64 – SirTobi

+0

如果您执行'np.reshape(x,(x.shape [0],-1))',并且它的工作原理是什么形状,会发生什么?有? – MSeifert

回答

0

如果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的文档解释:

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

+0

非常感谢您的解决方法!即使我把int(x.shape [1] * x.shape [2])它不起作用并显示一个新的错误: TypeError:只能将长度为1的数组转换为Python标量 – SirTobi

+2

@SirTobi,我看到你接受了这个答案,但是错误的来源仍然是神秘的。任何机会,你可以添加一个自包含的,可运行的例子,以便我们对这个问题感到好奇的人可以尝试重现它? –

+0

@SirTobi什么......这真的很神秘。 x.shape [1] * x.shape [2]'怎样才能成为一个NumPy数组。 – MSeifert