2012-12-22 92 views
-1

爲什麼此代碼無法正常工作?我不能讓這個numpy數組正確調整大小。Python NumPy無法正確調整大小

import numpy 
a = numpy.zeros((10,10)) 
a[3,2] = 8 
a.resize((5,5)) 
if a[3,2] == 8: 
    print "yay" 
else: 
    print "not working" 
raw_input() 
+5

你期望發生的,什麼是真正發生什麼? –

回答

6

從文檔[help(a.resize)]:

Shrinking an array: array is flattened (in the order that the data are 
stored in memory), resized, and reshaped: 

>>> a = np.array([[0, 1], [2, 3]], order='C') 
>>> a.resize((2, 1)) 
>>> a 
array([[0], 
     [1]]) 

在你的情況,[3,2]被當作爲一個扁平的數據列表考慮存儲在索引32:

>>> a = numpy.zeros((10,10)) 
>>> a[3,2] = 8 
>>> list(a.flat).index(8) 
32 

32> = 25,所以你的改變不會在重新調整。如果你只是想只保留了幾個值的,那麼你可以使用

>>> a = a[:5, :5] 
>>> a 
array([[ 0., 0., 0., 0., 0.], 
     [ 0., 0., 0., 0., 0.], 
     [ 0., 0., 0., 0., 0.], 
     [ 0., 0., 8., 0., 0.], 
     [ 0., 0., 0., 0., 0.]]) 
>>> a[3,2] 
8.0 

,或者如果你真的願意,你可以通過調整大小前拷貝數據:

>>> a = numpy.zeros((10,10)) 
>>> a[3,2] = 8 
>>> a.flat[:(5*5)] = a[:5, :5].flat 
>>> a.resize((5,5)) 
>>> a[3,2] 
8.0 

,但我不不太明白這一點。 [我不記得調整大小如何處理內存,但我不會擔心。]

2

從文檔,http://docs.scipy.org/doc/numpy/reference/generated/numpy.resize.html

numpy.resize(一,new_shape)

返回具有指定形狀的新陣列。

如果新數組大於原始數組,則新數組填充a的重複副本。請注意,此行爲不同於a.resize(new_shape),它使用零填充而不是a的重複副本。

對於你希望你需要手動複製你想要的新陣列,以保持價值觀的行爲,像

a=a[:5,:5] 
+0

由於上面解釋的原因,這將產生一個零矩陣。 – DSM

+0

你打敗了我,當你回答時我正在編輯我的答案:( – ailnlv

+0

; ^)發生在我們所有人身上。這裏,+1。 – DSM

相關問題