Gianni Spear
Gianni Spear

Reputation: 8010

Python: two questions about a "numpy.ndarray"

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

Upvotes: 1

Views: 104

Answers (1)

BrenBarn
BrenBarn

Reputation: 251578

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

Upvotes: 3

Related Questions