In this section, we address the methods NumPy offers for access and modification of data in an array. Python itself provides a rich set of indexing modes, and NumPy extends these with a number of methods suitable for numerical computations.
To access items of an array a, NumPy, as Python, uses the a[...] bracket notation. In the background, NumPy defines the __getitem__, __setitem__, and __deleteitem__ methods to do the requested operations on the array items. The arguments inside the brackets are expressions that specify the locations of the items we want to access. For example, to access the element at position (1,2) of the two-dimensional array a, we use the expression a[1,2]. Since indexing starts at 0, the expression refers to the item in the second row and third column of the array.
It is also valid to use negative indices to refer to positions from the end of the array. For instance, the last item of a row with index 2 can be referred to as a[2,-1].
Before moving on to the recipes in this section, let's define a function to help visualize arrays using the following code:
def dumpArray(arr):
print(' '.join([
' '.join(['{:02d}'.format(elem) for elem in row])
for row in arr
]))
To make the examples concrete, we will use an array x, defined as follows:
m = n = 10
x = np.array([np.arange(n) + m*i for i in range(n)])
Using the code dumpArray(x), we can display the contents of the array x, as follows:
00 01 02 03 04 05 06 07 08 09
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
...
90 91 92 93 94 95 96 97 98 99
Notice that the array x is defined in such a way that its elements reflect their position in the array.