Indexing and slicing ¶
In Python, the colon
:
is used for
slicing
in sequences, such as strings, lists, and NumPy arrays.
The syntax for slicing is generally
start:stop:step
.
Here's an explanation of each part:
-
start
: The index at which the slice begins (inclusive). If omitted, it defaults to the beginning of the sequence. -
stop
: The index at which the slice ends (exclusive). If omitted, it defaults to the end of the sequence. -
step
: The step size or the number of indices between each slice. If omitted, it defaults to 1.
array = np.array(
[
[0, 1, 2, 3, 4, 5],
[10, 11, 12, 13, 14, 15],
[20, 21, 22, 23, 24, 25],
[30, 31, 32, 33, 34, 35],
[40, 41, 42, 43, 44, 45],
[50, 51, 52, 53, 54, 55],
]
)
print(array)
[[ 0 1 2 3 4 5] [10 11 12 13 14 15] [20 21 22 23 24 25] [30 31 32 33 34 35] [40 41 42 43 44 45] [50 51 52 53 54 55]]
array[0]
array([0, 1, 2, 3, 4, 5])
array[0, 3:5]
array([3, 4])
array[4:, 4:]
array([[44, 45], [54, 55]])
array[:, 2]
array([ 2, 12, 22, 32, 42, 52])
array[2::2, ::2]
array([[20, 22, 24], [40, 42, 44]])
Another way to think about slicing is by specifying coordinates in the array. The intuition behind NumPy slicing as coordinates lies in pinpointing specific locations or regions within an array based on their positions along each dimension. Consider a 2D array as a grid of values, where each cell corresponds to a specific combination of row and column indices. When you use slicing in NumPy, you specify ranges of indices along each dimension, similar to coordinates on a grid.
For example, if you have a 2D array arr representing a grid of values,
arr[i:j, k:l]
would specify a rectangular region in the grid.
Here,
i
and
j
represent the range of row indices, and
k
and
l
represent the range of column indices.
This is analogous to specifying coordinates for a rectangle's top-left and bottom-right corners.
The ability to slice arrays in this way provides:
- A natural and efficient means of working with data at specific positions or regions.
- Making NumPy a versatile tool for tasks like image processing.
- Scientific computing.
- Data analysis.