Python - NumPy Part 2: Array Indexing and Slicing
Efficient data access is a key feature of NumPy, enabling indexing and slicing of arrays.
Examples and Explanation
Indexing Elements
array = np.array([10, 20, 30, 40])
print(array[2]) # Output: 30
Explanation: Access elements using zero-based indexing.
Slicing Arrays
print(array[1:3]) # Output: [20 30]
Explanation: Use slicing to access a subset of the array. The start index is inclusive, and the end index is exclusive.
Indexing in 2D Arrays
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix[1, 2]) # Output: 6
Explanation: Use [row, column] indexing for 2D arrays.
Slicing Rows and Columns
print(matrix[:, 1]) # Output: [2 5]
Explanation: The colon (:) selects all rows, and 1 selects the second column.
Boolean Indexing
print(array[array > 20]) # Output: [30 40]
Explanation: Apply conditions to filter elements. This feature is useful in data cleaning and analysis.