To illustrate indexing, let's first create an array with random data using the following command:
import numpy.random a = np.random.rand(6,5) print a
This creates an array of dimension (6,5)
that contains random data. Individual elements of the array are accessed with the usual index notation, for example, a[2,4]
.
An important technique to manipulate data in NumPy
is the use of slices. A slice can be thought of as a subarray of an array. For example, let's say we want to extract a subarray with the middle two rows and first two columns of the array a
. Consider the following command lines:
b = a[2:4,0:2] print b
Now, let's make a very important observation. A slice is simply a view of an array, and no data is actually copied. This can be seen by running the following commands:
b[0,0]=0 print a
So, changes in b
affect the array a
! If we really need a copy, we need to explicitly say we want one. This can be done using the following command line:
c = np.copy(a[2:4,0:2]) c[0,0] = -1 print a
In the slice notation i:j
, we can omit either i
or j
, in which case the slice refers to the beginning or end of the corresponding axis:
print a[:4,3:]
Omitting both i
and j
refers to a whole axis:
print a[:,2:4]
Finally, we can use the notation i:j:k
to specify a stride k
in the slice. In the following example, we first create a larger random array to illustrate this:
a = np.random.rand(10,6) print a print print a[1:7:2,5:0:-3]
Let's now consider slices of higher dimensional arrays. We will start by creating a really large three-dimensional array as follows:
d1, d2, d3 = 4, 5, 3 a = np.random.rand(d1, d2, d3) print a
Suppose we want to extract all elements with index 1
in the last axis. This can be done easily using an ellipsis object as follows:
print a[...,1]
The preceding command line is equivalent to the following one:
print a[:,:,1]
It is also possible to augment the matrix along an axis when slicing, as follows:
print a[0, :, np.newaxis, 0]
Compare the output of the preceding command line with the output of the following:
print a[0, :, 0]