In this tutorial, you will learn how to extract one or more elements from a NumPy array using slicing techniques on both one-dimensional and multidimensional arrays.

Slicing One-Dimensional Arrays

NumPy uses bracket [] and colon : notation for slicing arrays, just like Python lists.

Syntax

a[m:n]

Selects elements from index m up to but not including index n.

This is equivalent to:

a[m:n:1]

To skip every k elements:

a[m:n:k]

To reverse elements:

a[::-1]

Common Slicing Patterns

Expression Description
a[m:n] Select elements from index m to n-1
a[:] or a[0:-1] Select all elements
a[:n] From beginning up to index n-1
a[m:] From index m to the end
a[m:-1] From index m to the second last element
a[m:n:k] Select with step k
a[::-1] All elements in reverse order

Example

import numpy as np

a = np.arange(0, 10)

print('a =', a)
print('a[2:5] =', a[2:5])
print('a[:] =', a[:])
print('a[0:-1] =', a[0:-1])
print('a[0:6] =', a[0:6])
print('a[7:] =', a[7:])
print('a[5:-1] =', a[5:-1])
print('a[0:5:2] =', a[0:5:2])
print('a[::-1] =', a[::-1])

Output:

a = [0 1 2 3 4 5 6 7 8 9]
a[2:5] = [2 3 4]
a[:] = [0 1 2 3 4 5 6 7 8 9]
a[0:-1] = [0 1 2 3 4 5 6 7 8]
a[0:6] = [0 1 2 3 4 5]
a[7:] = [7 8 9]
a[5:-1] = [5 6 7 8]
a[0:5:2] = [0 2 4]
a[::-1] = [9 8 7 6 5 4 3 2 1 0]

Slicing Multidimensional Arrays

To slice multidimensional arrays, use slicing syntax for each axis, separated by commas.

Example 1

import numpy as np

a = np.array([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
])

print(a[0:2, :])

Output:

[[1 2 3]
 [4 5 6]]

Explanation:

  • 0:2 selects the first two rows.

  • : selects all columns.

Example 2

print(a[1:, 1:])

Output:

[[5 6]
 [8 9]]

Explanation:

  • 1: selects from the second row to the end.

  • 1: selects from the second column to the end.

Summary

  • Use slicing to extract sub-arrays from NumPy arrays.

  • One-dimensional slicing follows the form a[m:n:p].

  • Multidimensional slicing uses a[m:n, i:j, ...] with each axis sliced individually.

  • Use step values and negative indices to reverse or skip elements as needed.