1

I created a numpy.ndarray with value

import numpy as np from numpy import nonzero

data = np.zeros((5, 5))
data
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.]])

i wish to change some values with 1

data[0,0] = 1
data[4,4] = 1

data
array([[ 1.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  1.]])

if i change 0 with 5 using negative values i have

data[-5,-5] = 5
data[-4,-4] = 5

>>> data
array([[ 5.,  0.,  0.,  0.,  0.],
       [ 0.,  5.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])

1- I don't understand why i have not an error message as

>>> data[10,10] = 5
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
IndexError: index (10) out of range (0<=index<5) in dimension 0

2- it's not clear why with data[-5,-5] = 5 and data[-4,-4] = 5 the value 5 is inserted in position 0,0 and 1,1

1 Answer 1

3

From the documentation:

Negative indices are interpreted as counting from the end of the array

This is the standard Python indexing behavior (used in Python lists, etc.).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks BrenBarn, I skipped that sentence. Thanks again

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.