import numpy as np 8 Slicing Data
Slicing is the process of selecting a subset of an array. We start by importing numpy.
8.1 Slicing in 1-D
Given a 1-D NumPy array named vec, the syntax to select a range of indices is: \[\text{vec} [\text{start} : \text{stop} : \text{step}]\] where \(\text{start}\) is the starting index, \(\text{stop}\) is the excluded stopping index, and \(\text{step}\) is an increment. Consider the array:
vec = np.array([10, 20, 30, 40, 50, 60, 70, 80])which has the structure:
The following examples are slices of vec:
| Slice | Result | Description |
|---|---|---|
vec[1:4] |
[20, 30, 40] |
Elements from index 1 up to 4 (excluded) |
vec[:3] |
[10, 20, 30] |
Elements up to index 3 (excluded) |
vec[3:] |
[40, 50, 60, 70, 80] |
Elements from index 3 to the end |
vec[1:5:3] |
[20, 50] |
From index 1 to 5 (excluded) skipping by 3 |
vec[2::2] |
[30, 50, 70] |
Elements from 2 to the end, skipping by 2 |
Notice that we sometimes leave out numbers around the : character. The slice vec[:3] says that we start at the beginning and go up to but not including index 3. The slice vec[3:] starts at index \(3\) and goes up to the end.
Specifying Indices
We are not constrained to selecting only sequential elements from an array. We can select arbitrary elements by passing a list of which indices we want to select:
vec = np.array([10, 20, 30, 40, 50, 60, 70, 80])
vec[ [1,5,6] ]array([20, 60, 70])
8.2 Negative Indices
Negative indices count backwards, so a[-1] refers to the last element in a and a[-2] references the second to last element in a.
The step in \(\text{vec} [\text{start} : \text{stop} : \text{step}]\) can also be negative. Stepping by \(-1\) means moving backwards through an array, so that we can effectively reverse an array with:
vec = np.array([10, 20, 30, 40, 50, 60, 70, 80])
print( vec[::-1] )[80 70 60 50 40 30 20 10]
8.3 Slicing in 2-D
8.3.1 Rows and Columns
Slicing a 2-D array requires specifying rows and columns (in that order). Consider an array arr:
arr = np.array([[10, 20, 30, 40],
[50, 60, 70, 80],
[90, 100, 110, 120]])
To select the element \(80\) from this array, we would specify row 1 with column 3:
print( arr[1,3] )80
Notice that this returns the value \(80\) and not a subarray containing the value 80. Indexing a single element within an array references the value at that position.
We can select the entire middle row by specifying row 1 and using : to represent “all” columns:
print( arr[1,:] )[50 60 70 80]
We can select the last column by specifying any row : and column 3:
print( arr[:,3] )[ 40 80 120]
8.4 Updating Values
8.4.1 Update an element
When we use an expression like arr[1,2], we are referencing the element at that row and column. We can print as we did above, or we can assign new values. For example:
arr = np.array([[10, 20, 30, 40],
[50, 60, 70, 80],
[90, 100, 110, 120]])
arr[1,2] = -1
print(arr)[[ 10 20 30 40]
[ 50 60 -1 80]
[ 90 100 110 120]]
8.4.2 Update Rows or Columns
We can update subarrays, including entire rows, columns, or the entire array with the same operations we used in Chapter 3. Below, we assign a new value to the third row (index 2) to be equal to \(3\) times its current value in each place.
arr = np.array([[10, 20, 30, 40],
[50, 60, 70, 80],
[90, 100, 110, 120]])
arr[2] = arr[2] * 3
print(arr) [[ 10 20 30 40]
[ 50 60 70 80]
[270 300 330 360]]
Exercises
Given
vec = np.array([10, 20, 30, 40, 50, 60, 70, 80])Determine by hand the result of the following slices, then validate your work with code.
vec[2:6]vec[:4]vec[::3]vec[1::2]vec[-3:]vec[:-2]vec[-1]vec[5:2]vec[::-2]
Using the same vector
vecfrom the previous question, write the slices that would produce each of these results:[30, 40, 50, 60, 70, 80][10, 30, 50, 70][80, 70, 60, 50, 40, 30, 20, 10][70, 50, 30][20, 60, 70][40, 40, 40]
Use slicing to set all of the non-zero elements of
Mto \(1\):M = np.array([[ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 1, 7, 0, 0, 0, 0], [ 0, 0, 4, 3, 0, 0, 0, 0], [ 0, 0, 9, 2, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0]])Given the following array:
A = np.array([[ 10, 20, 30, 40, 50], [ 60, 70, 80, 90, 100], [110, 120, 130, 140, 150], [160, 170, 180, 190, 200]])Write an expression to select each of the following:
- The third row.
- The second column.
- The value 50.
- The last row, using a negative index.
- The first two columns, all rows.
- The block containing 80, 90, 100, 130, 140, and 150.
- Every other row and every other column, starting from the top left.
Start with the array
Ain the previous problem. Write the code to:- Set the value 130 to 0.
- Multiply the entire first column by 10.
- Replace the last row with all zeros.
- Set the four corner values to \(-1\), using at most two lines of code.
- Reverse the order of the columns.
Given a 1-D array named
TwoHundocontaining two hundred random digits, write the one line of code that would set every other element ofTwoHundoequal to \(0\), beginning with the second element. Create such an array and demonstrate your working one-liner.