Slicing multi-dimensional arrays in Python

import numpy as np

# Creating a 2D array (matrix)
arr = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])

print(arr)

# Accessing the second row (index 1)
print(arr[1])

# Accessing the third column (index 2)
print(arr[:, 2])

# Slice a subarray from rows 1 to 2 (not including 3), columns 1 to 3 (not including 4)
print(arr[1:3, 1:4])

# Slice every other row and column
print(arr[::2, ::2])

arr_3d = np.array([[[1, 2], [3, 4]],
[[5, 6], [7, 8]],
[[9, 10], [11, 12]]])

print(arr_3d)

# Select the second row from all matrices
print(arr_3d[:, 1, :])

# Select rows 0 to 1 and columns 0 to 1 from all matrices
print(arr_3d[:, :2, :2])
print(arr_3d[::2, ::2, ::2])

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top