NumPy Array Slicing in Python

Share this article

In Python, NumPy array slicing allows you to extract or modify specific portions of an array. Slicing involves specifying a range of indices to access a subset of the array, similar to how you slice lists in Python.

Key Takeaway

NumPy array slicing is a powerful way to extract, modify, or manipulate specific portions of an array using a range of indices. It enables efficient access to data in multi-dimensional arrays for analysis or transformation.

Example

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(arr[1:4])  

# Output: [2 3 4]

What it does

In this example, arr[1:4] slices the array from index 1 up to, but not including, index 4. This extracts the subarray [2, 3, 4] from the original array.

  • Start index: The slice starts at the index you specify.
  • End index: The slice ends one step before the index you specify as the end.

Examples

Example 1: Slicing with step

arr = np.array([1, 2, 3, 4, 5, 6])

print(arr[1:6:2])  

# Output: [2 4 6]

This slices the array starting at index 1, ending at index 6 (not included), and selecting every second element. The result is [2, 4, 6].

Example 2: Negative indexing

arr = np.array([10, 20, 30, 40, 50])

print(arr[-4:-1])  

# Output: [20 30 40]

Negative indices allow slicing from the end of the array. In this case, the slice starts from the second element from the start (-4) and ends at the last element (-1), but it does not include the last element.

Example 3: Multi-dimensional array slicing

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

print(arr[0:2, 1:3])

# Output: 
# [[2 3]
#  [5 6]]

In multi-dimensional arrays, you can slice across both dimensions. Here, it extracts rows 0 to 1 (not including row 2) and columns 1 to 2 (not including column 3).

Example 4: Slicing the entire column

arr = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])

print(arr[:, 1])

# Output: [20 50 80]

You can extract an entire column by using a colon : to select all rows and specifying the column index. This extracts the second column from the array.