2017-08-28 16 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]))) 

これがなぜ起こり得るのかご存知ですか?

ありがとうございます!

編集:

これは私が実行しているコードであり、それはreshapeのための第二引数の一つの要素が整数でない場合は、例外が唯一のため、起こるはずのエラー

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

を生成例:

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

ありがとうございました! TypeError:長さ1の配列だけをPythonスカラーに変換する – SirTobi

+2

@SirTobi、@SirTobi、私はあなたがこの答えを受け入れたのを見るが、エラーの原因はまだ不思議である。私たちが問題を好奇心を持っている人が再現しようとするように、自己完結型の実行可能な例を追加することはできますか? –

+0

@SirTobi何が...これは本当に神秘的になっています。 'x.shape [1] * x.shape [2]'はどのようにNumPyの配列になりますか? – MSeifert