Indexing

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.

In NumPy, it is common to use notation, as in the preceding example, to index items in multidimensional arrays. This notation is possible because, in Python, arr[i, j, k, ...] can be used as shorthand for arr[(i, j, k, ....)]. Notice, however, that this behavior is defined in the ndarray class, and it is not possible, for example, to use multi-indices with pure Python lists of lists. 

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

As a general rule, a negative index -j refers to the item at position n-j, where n is the length of the axis along which the index is being used. This assumes that n-j is not negative.

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset