2017-08-28 52 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