0

I am looking for replacing zones in array, for example I create an array b = numpy.zeros((12,12)). And I want to change its values with a=numpy.aray([[1,2],[2,3]]) in the left upper corner indexed by [0:1,0:1].

When I specify b[0:1,0:1] = a I have an error:

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

What's the method to do such thing ?

Thanks

1
  • numpy uses the same conventions as Python for slicing. For the basics of Python slicing, see this question. Commented Oct 21, 2012 at 18:45

1 Answer 1

6

Use correct indices:

>>> 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.]])

From 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
Sign up to request clarification or add additional context in comments.

3 Comments

That's it! I don't really understand why because i want to replace the index 0 and 1 (fon example in one line). Why is it necessary to go to index 2 ?
@user1187727 Because 2 denotes the end of the second element (see the scheme at the end of my answer). So [0:2] is actually the first and the second elements of the sequence.
Ok nice response ! Thank you very much !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.