Indexing and Slicing
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...