Indexing and slicing arrays

Introduction to NumPy

Izzy Weber

Core Curriculum Manager, DataCamp

Indexing 1D arrays

array = np.array([2, 4, 6, 8, 10])
array[3]
8
Introduction to NumPy

Indexing elements in 2D

A sudoku game with a single number selected in the third row of the fifth column

 

 

sudoku_game[2, 4]
6
Introduction to NumPy

Indexing rows in 2D

A sudoku game with the first row selected

 

 

sudoku_game[0]
array([0, 0, 4, 3, 0, 0, 2, 0, 9])
Introduction to NumPy

Indexing columns in 2D

A sudoku game with the fourth column selected

 

 

sudoku_game[:, 3]
array([3, 0, 0, 0, 0, 0, 0, 5, 9])
Introduction to NumPy

Slicing 1D arrays

array = np.array([2, 4, 6, 8, 10])
array[2:4]
array([6,  8])
Introduction to NumPy

Slicing 2D arrays

A sudoku game with the middle nine squares selected - columns four to six and rows four to six

 

 

sudoku_game[3:6, 3:6]
array([[0, 0, 2],
       [0, 0, 7],
       [0, 8, 3]])
Introduction to NumPy

Slicing with steps

A sudoku game with only the corners of the middle nine boxes selected

 

 

sudoku_game[3:6:2, 3:6:2]
array([[0, 2],
       [0, 3]])
Introduction to NumPy

Sorting arrays

Before sorting: An unsorted sudoku game

np.sort(sudoku_game)
array([[0, 0, 0, 0, 0, 2, 3, 4, 9],
       [0, 0, 0, 0, 0, 0, 1, 5, 9],
       [0, 0, 0, 0, 0, 3, 4, 6, 7],
       [0, 0, 0, 0, 0, 2, 6, 7, 8],
       [0, 0, 0, 0, 0, 1, 4, 7, 9],
       [0, 0, 0, 0, 0, 0, 3, 5, 8],
       [0, 0, 0, 0, 0, 0, 1, 5, 6],
       [0, 0, 0, 0, 3, 5, 6, 8, 9],
       [0, 0, 0, 0, 1, 2, 3, 4, 9]])
Introduction to NumPy

Axis order

 

graphic showing that axis zero is the direction along rows and axis one is the direction along columns

 

Graphic showing that the number one looks like a column

Introduction to NumPy

Sorting by axis

np.sort(sudoku_game)
array([[0, 0, 0, 0, 0, 2, 3, 4, 9],
       [0, 0, 0, 0, 0, 0, 1, 5, 9],
       [0, 0, 0, 0, 0, 3, 4, 6, 7],
       [0, 0, 0, 0, 0, 2, 6, 7, 8],
       [0, 0, 0, 0, 0, 1, 4, 7, 9],
       [0, 0, 0, 0, 0, 0, 3, 5, 8],
       [0, 0, 0, 0, 0, 0, 1, 5, 6],
       [0, 0, 0, 0, 3, 5, 6, 8, 9],
       [0, 0, 0, 0, 1, 2, 3, 4, 9]])
np.sort(sudoku_game, axis=0)
array([[0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 2, 0, 0, 2, 1, 0, 1],
       [0, 4, 3, 0, 0, 3, 2, 0, 3],
       [0, 5, 4, 3, 1, 7, 3, 4, 5],
       [1, 7, 5, 5, 6, 8, 4, 8, 7],
       [6, 9, 6, 9, 8, 9, 6, 9, 9]])
Introduction to NumPy

Let's practice!

Introduction to NumPy

Preparing Video For Download...