2012-10-21 46 views
0

我正在尋找替換數組中的區域,例如我創建了一個數組b = numpy.zeros((12,12))。我想在[0:1,0:1]的左上角用a=numpy.aray([[1,2],[2,3]])更改它的值。Numpy數組和更改值區域

當我指定b[0:1,0:1] = a我有一個錯誤:

"ValueError: output operand requires a reduction, but reduction is not enabled". 

什麼是做這種事的方法?

感謝

+0

'numpy'使用相同的約定的Python切片。有關Python切片的基礎知識,請參見[此問題](http://stackoverflow.com/q/509211/577088)。 – senderle

回答

4

使用正確的指標:

>>> b[0:2,0:2] = a 
>>> b 
array([[ 1., 2., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], 
     [ 2., 3., 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., 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., 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., 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., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]) 

the docs

One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example:

+---+---+---+---+---+ 
| H | e | l | p | A | 
+---+---+---+---+---+ 
0 1 2 3 4 5 
-5 -4 -3 -2 -1 
+0

就是這樣!我不明白爲什麼,因爲我想替換索引0和1(例如在一行中)。爲什麼有必要去索引2? – user1187727

+0

@ user1187727因爲'2'表示第二個元素的結束(請參閱我的答案結尾處的方案)。所以[0:2]實際上是序列的第一個和第二個元素。 – ovgolovin

+0

好的回覆!非常感謝你 ! – user1187727