1>>> import numpy as np
2>>> myarray = np.arange(10)
3>>> myarray
4array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
5>>>
6
As you can see, for arrays, indexing starts with 0. We have a few examples of selecting values below. In the first example, we select a single value at index 5 (6th value in the array). In the second example, we select all the elements of the array starting with index 2. In the third example,we specify the index range as 2 to 6. This will select all elements starting from index 2 upto but not including index 6. In the last example, we select all values except the last (-1).
1>>> myarray[5]
25
3>>> myarray[2:]
4array([2, 3, 4, 5, 6, 7, 8, 9])
5>>> myarray[2:6]
6array([2, 3, 4, 5])
7>>> myarray[:-1]
8array([0, 1, 2, 3, 4, 5, 6, 7, 8])
9>>>
10
Slicing is possible over all dimensions. Let's look at some examples of slicing in a two-dimensional array. Let's say we have the following 2-d array:
1>>> array2d = np.array([[10,20,30],[40,50,60]])
2>>> array2d
3array([[10, 20, 30],
4 [40, 50, 60]])
5>>>
6
Following are a few examples of slicing this array:
1>>> array2d[1,1]
250
3>>> array2d[0,2]
430
5>>>
6
Data Assignment
We can assign values to slices of arrays as follows:
1>>> myarray
2array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
3>>> myarray[2:6] = 100
4>>> myarray
5array([ 0, 1, 100, 100, 100, 100, 6, 7, 8, 9])
6>>>
7
As you can see, if you assign a scalar value to a slice, as in myarr[2:6] = 100
, the value is broadcasted to the entire selection. An important distinction from lists is that array slices are views on the original array. This means that the data is not copied, and any modifications to the view will be reflected in the source array.
Exercises
You would notice that some concepts in the exercises below are not taught. Feel free to google or ask in forums.
- Create an array with 50 elements. Then create another array which is a reverse of the first array.
- Create an array with 10 random values and then sort it.
- Create a 5x5 matrix using arrange and reshape functions. Then select all the elements from the third row.
- Create a null vector of size 10 but the fourth value which is 1.