Array Indexing in NumPy
How indexinf is used in NumPy arrays.
Indexing in NumPy allows you to access or modify specific elements in an array. It works similarly to Python lists but supports multi-dimensional indexing.
Indexing in 1D Arrays
A 1D NumPy array behaves like a Python list.
Accessing Elements
import numpy as np
# Creating a 1D array
arr = np.array([10, 20, 30, 40, 50])
print(arr[0]) # First element
print(arr[2]) # Third element
print(arr[-1]) # Last element
Output:
10
30
50
Negative indexing works just like in lists (-1
is the last element).
Indexing in 2D Arrays
For multi-dimensional arrays, we specify row and column indices.
Accessing Elements in a 2D Array
arr = np.array([[10, 20, 30],
[40, 50, 60],
[70, 80, 90]])
print(arr[0, 0]) # First row, first column
print(arr[1, 2]) # Second row, third column
print(arr[-1, -1]) # Last row, last column
Output:
10
60
90
Syntax: arr[row, column]
Indexing in 3D Arrays
A 3D array consists of multiple 2D arrays (matrices).
The indexing follows this pattern:
arr[depth, row, column]
Accessing Elements in a 3D Array
arr = np.array([[[1, 2, 3],
[4, 5, 6]],
[[7, 8, 9],
[10, 11, 12]]])
print(arr[0, 1, 2]) # First matrix, second row, third column
print(arr[1, 0, 1]) # Second matrix, first row, second column
Output:
6
8
Visualizing the 3D Array:
Matrix 1: Matrix 2:
[[1, 2, 3] [[7, 8, 9]
[4, 5, 6]] [10,11,12]]
Modifying Elements Using Indexing
You can update elements using their index positions.
Modifying Array Elements
arr = np.array([10, 20, 30])
arr[1] = 50 # Change second element to 50
print(arr)
Output:
[10 50 30]
Indexing Using Boolean Conditions
You can filter elements using boolean indexing.
# Get Elements Greater Than 20
arr = np.array([10, 20, 30, 40, 50])
filtered_arr = arr[arr > 20] # Get elements greater than 20
print(filtered_arr)
Output:
[30 40 50]
Use Case: This is useful for filtering datasets in data science.
Summary
- 1D Indexing: Use simple indices (
arr[2]
) - 2D Indexing: Use row and column indices (
arr[1, 2]
) - 3D Indexing: Use depth, row, column (
arr[0,1,2]
) - Modifying Elements: Assign new values using indices
- Boolean Indexing: Filter elements based on conditions