2010-06-17 72 views
6

下面的例子顯示了我想做的事:的Python NumPy的結構數組(recarray)分配值成片

>>> test 
rec.array([(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), 
    (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0)], 
    dtype=[('ifAction', '|i1'), ('ifDocu', '|i1'), ('ifComedy', '|i1')]) 

>>> test[['ifAction', 'ifDocu']][0] 
(0, 0) 

>>> test[['ifAction', 'ifDocu']][0] = (1,1) 
>>> test[['ifAction', 'ifDocu']][0] 
(0, 0) 

所以,我希望將值分配給(1,1)test[['ifAction', 'ifDocu']][0]。 (最後,我要像做test[['ifAction', 'ifDocu']][0:10] = (1,1),爲0:10分配相同的值。我已經嘗試了許多方法,但都沒成功。有沒有辦法做到這一點?

謝謝 俊

+1

另請參閱@HYRY [回答稍微不同的問題](http://stackoverflow.com/a/21819324/347815),它可以很好地解決這個問題。 – katahdin 2014-06-09 14:42:02

回答

4

當你說test['ifAction']你得到了一個數據視圖 當你說test[['ifAction','ifDocu']]你正在使用花式索引,從而得到一份數據的副本,該副本不會幫助你,因爲修改副本將保留原始數據不變

因此,解決此問題的方法是將值分配給test['ifAction']test['ifDocu']個別:

test['ifAction'][0]=1 
test['ifDocu'][0]=1 

例如:

import numpy as np 
test=np.rec.array([(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), 
    (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0)], 
    dtype=[('ifAction', '|i1'), ('ifDocu', '|i1'), ('ifComedy', '|i1')]) 

print(test[['ifAction','ifDocu']]) 
# [(0, 0) (0, 0) (0, 0) (0, 0) (0, 0) (0, 0) (0, 0) (0, 0) (0, 0) (0, 0)] 
test['ifAction'][0]=1 
test['ifDocu'][0]=1 

print(test[['ifAction','ifDocu']][0]) 
# (1, 1) 
test['ifAction'][0:10]=1 
test['ifDocu'][0:10]=1 

print(test[['ifAction','ifDocu']]) 
# [(1, 1) (1, 1) (1, 1) (1, 1) (1, 1) (1, 1) (1, 1) (1, 1) (1, 1) (1, 1)] 

對於引擎蓋下從深層次看,看到this post by Robert Kern

+0

非常感謝。所以問題在於現場訪問。 – joon 2010-06-17 03:21:22