NumPy Array Indexing
NumPy array indexing allows you to access and modify individual elements or groups of elements in an array. Understanding how to index arrays is fundamental for effective data manipulation in NumPy.
Indexing 1-D Arrays
Indexing in 1-D arrays is straightforward. You can access elements using their index, starting from 0.
Example: Accessing Elements in a 1-D Array
import numpy as np
# Creating a 1-D array
arr = np.array([10, 20, 30, 40, 50])
# Accessing elements
print(arr[0]) # Output: 10
print(arr[3]) # Output: 40
Indexing 2-D Arrays
In 2-D arrays, elements are accessed using a pair of indices. The first index refers to the row, and the second index refers to the column.
Example: Accessing Elements in a 2-D Array
import numpy as np
# Creating a 2-D array
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Accessing elements
print(arr[0, 2]) # Output: 3
print(arr[1, 1]) # Output: 5
Indexing 3-D Arrays
Indexing in 3-D arrays involves three indices. The first index is for the depth, the second for the row, and the third for the column.
Example: Accessing Elements in a 3-D Array
import numpy as np
# Creating a 3-D array
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
# Accessing elements
print(arr[0, 1, 2]) # Output: 6
print(arr[1, 0, 1]) # Output: 8
Slicing Arrays
Array slicing allows you to access subarrays by specifying a range of indices. The syntax for slicing is start:stop:step
.
Example: Slicing a 1-D Array
import numpy as np
# Creating a 1-D array
arr = np.array([10, 20, 30, 40, 50])
# Slicing the array
print(arr[1:4]) # Output: [20 30 40]
print(arr[:3]) # Output: [10 20 30]
print(arr[::2]) # Output: [10 30 50]
Example: Slicing a 2-D Array
import numpy as np
# Creating a 2-D array
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Slicing the array
print(arr[1:, 1:]) # Output: [[5 6]
# [8 9]]
print(arr[:2, ::2]) # Output: [[1 3]
# [4 6]]
Boolean Indexing
Boolean indexing allows you to select elements based on conditions. This is useful for filtering arrays.
Example: Boolean Indexing
import numpy as np
# Creating an array
arr = np.array([10, 20, 30, 40, 50])
# Boolean indexing
print(arr[arr > 25]) # Output: [30 40 50]
Fancy Indexing
Fancy indexing allows you to access multiple elements at once using lists or arrays of indices.
Example: Fancy Indexing
import numpy as np
# Creating an array
arr = np.array([10, 20, 30, 40, 50])
# Fancy indexing
indices = [1, 3, 4]
print(arr[indices]) # Output: [20 40 50]
Conclusion
In this chapter, we’ve explored various techniques for indexing and slicing NumPy arrays. Understanding these techniques is essential for efficient data manipulation and analysis in NumPy.