Python slicing multi-dimensional arrays
Python’s NumPy package makes slicing multi-dimensional arrays a valuable tool for data manipulation and analysis. It enables efficient subset data extraction and manipulation from arrays, making it a useful skill for any programmer, engineer, or data scientist.
Python Slicing Multi-Dimensional Arrays
Slicing is a method for taking out an array section frequently used for subsetting and modifying data inside arrays. In Python, Slicing gains considerably more strength when used with multi-dimensional arrays because it may be applied along several axes.
1-D Array Slicing
In a 1-D NumPy array, slicing is performed using the [start:stop: step] notation.
import numpy as np
arr = np.array([0, 1, 2, 3, 4, 5])
# Slice from index 1 to 3
sliced_arr = arr[1:4]
print(sliced_arr)
Output:
[1 2 3]
Multi-Dimensional Array Slicing
Now, let’s move on to slicing multi-dimensional arrays. Python NumPy allows you to slice arrays along each axis independently. This means you can extract rows, columns, or specific elements from a multi-dimensional array with ease.
Python Slicing Rows and Columns
In this example, we are slicing rows and columns.
# code
import numpy as np
matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# Slicing rows
# Get the first row
row_1 = matrix[0, :]
print(row_1)
# Slicing columns
# Get the second column
col_2 = matrix[:, 1]
print(col_2)
Output
[1, 2, 3]
[2 5 8]
Python Slicing Subarrays
In this example, we are slicing subarrays from a multi-dimensional array. This is useful when we want to extract a smaller portion of the array for further analysis or manipulation.
import numpy as np
matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# Slicing a subarray
# Get a 2x2 subarray
sub_matrix = matrix[0:2, 1:3]
print(sub_matrix)
Output
[[2 3]
[5 6]]
Slicing with Step in Python
In this example, we are using the step parameter in multi-dimensional array slicing to skip elements along each axis.
import numpy as np
matrix = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
# Slicing with step
# Skip every other row and column
sliced_matrix = matrix[::2, ::2]
print(sliced_matrix)
Output
[[ 1 3 ]
[ 9 11 ]]
Slicing using Negative Indexing in 2-D array
In this example, we are using negative indexing to slice in a 2-D array.
# Create a sample 2-D array (a list of lists)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Slicing using negative indexing to get the last row
last_row = matrix[-1]
print("Last Row:", last_row)
# Slicing using negative indexing to get the last element of the first row
last_element_first_row = matrix[0][-1]
print("Last Element of First Row:", last_element_first_row)
# Slicing using negative indexing to get the last two elements of the second row
last_two_elements_second_row = matrix[1][-2:]
print("Last Two Elements of Second Row:", last_two_elements_second_row)
Output
Last Row: [7, 8, 9]
Last Element of First Row: 3
Last Two Elements of Second Row: [5, 6]
Slicing along Multiple Axes in Python
In this example, we are slicing along multiple axes to extract specific elements from multi-dimensional arrays.
import numpy as np
matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# Combining slicing along rows and columns
sub_matrix = matrix[1:3, 0:2]
print(sub_matrix)
Output
[[4 5]
[7 8]]
Slicing using Negative Indexing in 3-D array
In this example, we first create a 3-D NumPy array called array_3d. Then, we use negative indexing to slice the last row from each 2-D matrix within the 3-D array. The slicing notation [:, :, -1] means that we’re selecting all elements along the first and second dimensions (rows and columns) and the last element along the third dimension (last row in each 2-D matrix).
import numpy as np
# Create a 3-D NumPy array
array_3d = np.array([
[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
[[10, 11, 12], [13, 14, 15], [16, 17, 18]],
[[19, 20, 21], [22, 23, 24], [25, 26, 27]]
])
# Display the original array
print("Original 3-D Array:")
print(array_3d)
# Slice the last column from each 2-D matrix
sliced_array = array_3d[:, :, -1]
# Display the sliced array
print("\nSliced 3-D Array (Last Column from Each 2-D Matrix):")
print(sliced_array)
Output
Original 3-D Array:
[[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]]
[[10 11 12]
[13 14 15]
[16 17 18]]
[[19 20 21]
[22 23 24]
[25 26 27]]]
Sliced 3-D Array (Last Row from Each 2-D Matrix):
[[ 3 6 9]
[12 15 18]
[21 24 27]]