2015-11-06 76 views
0

我試圖運行numpy.reshape()的一個簡單示例。從.py文件中調用時似乎不起作用,但是當我直接從Python終端嘗試時,它完美工作。numpy.reshape()在Python終端中工作,但不在.py文件中

我只是做:

import numpy as np 

a = np.arange(6) 
print a 
a.reshape((3,2)) 
print a 

它不會引發任何錯誤,但也不管用!下面是輸出:

Lucass-MacBook-Pro:LSTM lucaslourenco$ python theClass.py 
[0 1 2 3 4 5] 
[0 1 2 3 4 5] 

而在終端:

>>> import numpy as np 
>>> a = np.arange(6) 
>>> a 
array([0, 1, 2, 3, 4, 5]) 
>>> a.reshape((3,2)) 
array([[0, 1], 
     [2, 3], 
     [4, 5]]) 

簡單的解決方案?

回答

6

.reshape()返回一個新的對象,而不是就地修改a,所以你需要將結果指派回a

a = np.arange(6) 
a = a.reshape((3, 2)) 
print(a) 

還是在地方,你可以直接分配給其.shape要修改的屬性a

a = np.arange(6) 
a.shape = 3, 2 
print(a) 
+0

謝謝!我以爲我有一個更復雜的問題! –

相關問題