7.3. Extracting elements#
Interactive page
This is an interactive book page. Press launch button at the top right side.
It will often be useful to extract one or multiple elements from a NumPy array. To that end, we can use indexing and slicing. Let’s see how they work!
7.3.1. Indexing NumPy arrays#
We often need to access elements of an array, and we can do that in Python using square brackets:
a[n]
will give you the \(n^{th}\) element of array a
.
This process of extracting a single element from an array is called indexing. If we create an array such as this:
a = np.array([1, 2, 3, 4, 5])
you would perhaps expect that the first element of a
is 1
, and you can therefore access the first element of a
using a[1]
.
Let’s try it:
import numpy as np
a = np.array([1, 2, 3, 4, 5])
print(a[1])
However, this is wrong. Why? Because Python starts counting from zero: the first element of a
is actually a[0]
.
Why counting from zero?
This is a long-standing discussion among computer scientists, and the convention is different in many different programming languages. There are advantages and disadvantages of both, and even essays written about it. In any case, Python chose to start arrays at zero.
This also helps to better understand the range()
function: for example, to loop over all the elements of a
, we can use this code:
for i in range(len(a)):
n = a[i]
print('a[%d] is %d' % (i,n))
Here the len
function returns the length of the array a
, as we’ve seen before. Python has very smart for
loops that can automatically iterate over many types of objects, which means we can also print out all the elements of our array like this:
for n in a:
print(n)
In Python, if you try to index beyond the end of the array, you will get an error:
a[5]
Remember: indexing starts at zero!
Python also has a handy feature: negative indices count backwards from the end, so index -1
corresponds to the last element in the array.
a[-1]
a[-2]
We can also use indexing to change the values of elements in our array:
print(a)
a[2] = -1
print(a)
Set the first three and the last two entries of the following array to zero.
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 32, 55, 78, 22, 99, 55, 33.2, 55.77, 99, 101.3])
# Add code to set the first three and last two entries to zero
print(a)
Indexing two-dimensional arrays works by using commas inside square brackets to specify the index of the first and second dimension:
a = np.array(range(1,6))
m = np.outer(a,a)
print("Initial matrix:")
print(m)
# First index in the row number (counting from zero), second index in the column number
m[2,3] = -1
print("\nAfter changing entry [2,3] to -1:")
print(m)
7.3.2. Slicing NumPy arrays#
NumPy arrays also support a special type of indexing called slicing. Slicing returns a whole part of an array rather than just a single element.
To do this, we use not just a single number inside the square brackets, but instead two numbers, separated by a colon :
a[n:m]
will return all the elements of a
, starting at element n
and ending at element m-1
.
a = np.array(range(10))
print(a)
print(a[0:5])
The notation a[0:5]
has “sliced” out the first five elements of array \(a\).
With slicing, you can also leave out either n
or m
from the slice: if you leave out n
, it will default to n = 0
, and if you leave out m
, it will default to the end of the array (the same as m = -1
in Python indexing).
print(a[:5])
print(a[5:])
Also handy: you can have Python slice an array with a “step” size that is more than 1 by adding another :
and a number after that. Explore how it works:
print(a[0:10:2])
Fun: you can also use negative steps!
print(a[-1:-11:-1])
Unlike with indexing, Python is a bit lenient if you slice off the end of an array:
print(a[0:20])
Slicing can also be used to set multiple values in an array at the same time. Use slicing to set the first ten entries of the array below to zero in one line of code.
a = np.array(range(20))+1
print(a)
# Add code that sets the first 10 entries to zero
print(a)
You can also use slicing to assign values to an array from a vector, which can be a handy way to enter a matrix by hand:
m = np.zeros([3,3])
m[0,:] = [1,2,3]
m[1,:] = [4,5,6]
m[2,:] = [7,8,9]
print(m)
Similarly, slicing also can be used to extract rows, columns, or blocks of a matrix:
# A row
print(m[1,:])
# A column
print(m[:,1])
# Extract a block as a sub-matrix
print(m[1:,1:])
import micropip
await micropip.install("jupyterquiz")
from jupyterquiz import display_quiz
import json
with open("questions7.json", "r") as file:
questions=json.load(file)
display_quiz(questions, border_radius=0)