NumPy Array
Indexing
UNDERSTANDING ARRAY ELEMENT
ACCESS IN NUMPY
Introduction
Array indexing in NumPy is used to access specific elements within an
array.
It works similarly to Python lists but is more powerful, especially for
multi-dimensional arrays.
1. Accessing 1-D Array
Elements
• You can access a 1-D array element using its index number.
• Indexing starts from 0.
Examples:
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[0]) # Output: 1
print(arr[1]) # Output: 2
print(arr[2] + arr[3]) # Output: 7
2. Accessing 2-D Array
Elements
• A 2-D array can be visualized as rows and columns.
• Use [row_index, column_index] format to access elements.
Examples:
import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0, 1]) # Output: 2
print(arr[1, 4]) # Output: 10
3. Accessing 3-D Array
Elements
• For 3-D arrays, specify indices for depth, row, and column.
Example:
arr = np.array([[[1, 2, 3], [4, 5, 6]],
[[7, 8, 9], [10, 11, 12]]])
print(arr[0, 1, 2]) # Output: 6
COUNT…
Explanation:
• arr[0] → First dimension: [[1, 2, 3], [4, 5, 6]]
• arr[0, 1] → Second array from first dimension: [4, 5, 6]
• arr[0, 1, 2] → Third element: 6
Negative Indexing
Negative indexing is used to access elements starting from the end of
an array instead of the beginning.
import numpy as np
arr = np.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10]])
print(arr[1, -1]) # Output: 10
arr[1] → refers to the second row [6, 7, 8, 9, 10]
arr[1, -1] → refers to the last element in the second row → 10
NumPy Array Slicing
Slicing in NumPy allows extracting specific elements, rows, or subarrays
from a larger array using index ranges.
Format:
[start:end:step]
Slicing Basics
Components:
•start: The starting index (included).
•end: The stopping index (excluded).
•step: The interval between elements.
Defaults:
•start → 0
•end → length of array
•step → 1
Example 1 — Basic
Slicing
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
# Slicing from index 1 to 4
print(arr[1:5])
# Output: [2, 3, 4, 5]
# Slicing from index 4 to the end
print(arr[4:])
# Output: [5, 6, 7]
Negative Slicing
Use negative indices to slice elements from the end.
# Slicing from 3rd last to 2nd last index
print(arr[-3:-1])
# Output: [5, 6]
Using Steps
You can specify a step value to skip elements.
# Return every second element from index 1 to 4
print(arr[1:5:2])
# Output: [2, 4]
# Return every second element from the entire array
print(arr[::2])
# Output: [1, 3, 5, 7]
Slicing in 2-D Arrays
arr = np.array([
[1, 2, 3, 4, 5], # Row 0
[6, 7, 8, 9, 10] # Row 1
])
# From the second row (index 1), slice elements from index 1 to 3
print(arr[1, 1:4])
# Output: [7, 8, 9]
COUNT…
# Access the 3rd element (index 2) from both rows
print(arr[0:2, 2])
# Output: [3, 8]
0:2 → selects both rows.
,2 → selects the 3rd column.