DEV Community

Cover image for Understanding Indexing and Slicing in NumPy Arrays
Lohith
Lohith

Posted on • Updated on

Understanding Indexing and Slicing in NumPy Arrays

The concise explanation of indexing and slicing for NumPy ndarray objects:
Indexing: Similar to Python lists, NumPy ndarrays use zero-based indexing. The first element has an index of 0, the second has an index of 1, and so on. You can also use negative indices, where -1 refers to the last element, -2 to the second-to-last, and so forth.
Slicing: To extract a portion of an array, use the syntax array[start:end]. The start index is inclusive, while the end index is exclusive. For example, array[2:5] returns elements with indices 2, 3, and 4.

Let’s create an example 1-D array and explore different slicing scenarios step by step:

import numpy as np

# Create an array with elements from 0 to 9
array2 = np.arange(10)

# Slicing examples
full_array = array2[:]       # Full array
slice1 = array2[0:2]         # Slice from index 0 to 1 (inclusive)
slice2 = array2[:3]          # Slice from index 0 to 2 (inclusive)
slice3 = array2[3:]          # Slice from index 3 to the end
slice4 = array2[-3:-1]       # Slice from the third element from the end to the second element from the end

print("Full array:", full_array)
print("Slice [0:2]:", slice1)
print("Slice [:3]:", slice2)
print("Slice [3:]:", slice3)
print("Slice [-3:-1]:", slice4)
Enter fullscreen mode Exit fullscreen mode

Explanation:

Slice [0:2]: array2[0:2] includes elements at indices 0 and 1, resulting in [0, 1].
Slice [:3]: array2[:3] includes elements from index 0 to 2 (inclusive), giving [0, 1, 2].
Slice [3:]: array2[3:] starts from index 3 and includes all elements up to the end, resulting in [3, 4, 5, 6, 7, 8, 9].
Slice [-3:-1]: array2[-3:-1] includes elements at indices -3 and -2 (from the end), giving [7, 8].

Multi-dimensional slicing :-

Let’s break down multi-dimensional slicing in Python:
Syntax:
For a 2D array (matrix), the syntax is: array[row_slice, column_slice].
For an n-dimensional array, the syntax is: array[dim1_slice, dim2_slice, ..., dim_n_slice]
Slices:
Each dimension (axis) has its own slice. A slice specifies a range of indices to include.
Slices are defined using the colon (:) notation.
The start index is included, but the end index is excluded.

import numpy as np

# Creating a 2D NumPy array
arr = np.array([[67, 24, 90],
                [12, 39, 40],
                [9, 33, 58]])

# Using multi-dimensional slicing to extract specific elements
# Extracting the element at row index, column index 0
element = arr[0]
print("Element at index (0):", element)

# Using slicing to extract a subarray
# Extracting the subarray consisting of rows 0 and 1, and columns 1 and 2
sub_array = arr[0:2, 1:3]
print("Subarray:\n", sub_array)

# Using slicing to extract a subarray
# Extracting the subarray consisting of rows 0 and 2
sub_array_1 = arr[0:2]
print("Subarray_1:\n", sub_array_1)

# Using slicing to extract a subarray
#for both dimensions we have not defined the end index, so it means it will return all the elements from start of the given row index till end for both rows and columns.
sub_array_2 = arr[1:,2:]
print("Subarray_2:\n", sub_array_2)
Enter fullscreen mode Exit fullscreen mode
Element at index (0): [67 24 90]
Subarray:
 [[24 90]
 [39 40]]
Subarray_1:
 [[67 24 90]
 [12 39 40]]
Subarray_2:
 [[40]
 [58]]
Enter fullscreen mode Exit fullscreen mode

I hope these articles are being helpful.Please share some thoughts in the comments for the betterment.

Happy Learning🧑‍💻👨‍💻👩‍💻💯🚀

Top comments (0)