Tools
Text

Indexing

Lesson 10 Chapter 4

First, let's define and slice an array.

# Import Numpy library
import numpy as np

# Create a matrix
A = np.array([[2,1,3,4],[5,2,9,4],[5,2,10,1],[2,2,11,-1]])
print('A=\n', A)

# Extract the first two rows
# Remember 0:2 in indexing means {0,1} and does NOT include 2!
# Using : merely, means ALL!
print('The first two rows= \n', A[0:2,:])

# Extract the first three rows and the last two columns
# -2: means the second to the last to the end!
# 0:3 mean {0,1,2}
print('The first three rows and last two columns= \n', A[0:3,-2:])

# Let's point to one element
# The second row (index 1) and third column (index 2)
# Remember Python indexing starts from zero!!
print('The second row and third column= \n', A[1,2])

A=
	[[ 2  1  3  4]
	[ 5  2  9  4]
	[ 5  2 10  1]
	[ 2  2 11 -1]]
The first two rows= 
	[[2 1 3 4]
	[5 2 9 4]]
The first three rows and last two columns= 
	[[ 3  4]
	[ 9  4]
	[10  1]]
The second row and third column= 
	9
Left figure: Shows the A[0:4,-2:] which is the first three rows and the last two columns. Right figure: Shows A[1,2] which is only one single element located in second row and third column.

Let's review the code above. At line 11, I used sliced indexing by selecting from a range of indices. At line 21, I only used integer indices. We can simply combine both, but there might be a difference in the output matrix ranking. Check the example below:

# Import Numpy library
import numpy as np

# Create a matrix
A = np.array([[2,1,3,4],[5,2,9,4],[5,2,10,1],[2,2,11,-1]])
print('A=\n', A)

# Extract the first row and all colums using two approachs
print('The first row with slice indexing= \n', A[0:1,:]) # Slice indexing
print('The first row with integer indexing= \n', A[0,:])  # Integer indexing
print('The first row shape slice indexing= \n', A[0:1,:].shape) # Slice indexing
print('The first row shape integer indexing= \n', A[0,:].shape)  # Integer indexing

A=
	[[ 2  1  3  4]
	[ 5  2  9  4]
	[ 5  2 10  1]
	[ 2  2 11 -1]]
The first row with slice indexing= 
	[[2 1 3 4]]
The first row with integer indexing= 
	[2 1 3 4]
The first row shape slice indexing= 
	(1, 4)
The first row shape integer indexing= 
	(4,)

If you see the results, the shape of the matrix would be different. Basically, with slice indexing, we have a rank-2 matrix and with integer indexing, we will have a rank-1 matrix. Be careful about this difference when you are dealing with Numpy indexing.

Pen
Scroll to Top