Basic Indexing and Slicing Concepts
Indexing and slicing are your tools for extracting specific data from NumPy arrays. Think of indexing as pointing to exact locations, while slicing grabs entire sections in one go. Unlike Python lists that create copies, NumPy slicing creates views that share memory with the original array.
This memory-sharing behavior makes NumPy efficient but requires careful attention to avoid unintended modifications. The numpy.org provides extensive examples of advanced indexing patterns when you need more detailed data selection.
One-Dimensional Array Operations
One-dimensional arrays use the same syntax as Python lists. Slicing returns a view of the data, not a copy, so changes to the view will affect the original array.
import numpy as np# Create 1D arraya = np.linspace(0, 7, 8)print("Original array:", a) # Output: Original array: [0. 1. 2. 3. 4. 5. 6. 7.]# Single element indexingprint("3rd element:", a[3]) # Output: 3rd element: 3.0print("Last element:", a[-1]) # Output: Last element: 7.0# Basic slicingprint("Slice [2:6]:", a[2:6]) # Output: Slice [2:6]: [2. 3. 4. 5.]print("Slice [3:-2]:", a[3:-2]) # Output: Slice [3:-2]: [3. 4. 5.]# Modification through slicing (changes original array)a[:3] = 0print("After a[:3] = 0:", a) # Output: After a[:3] = 0: [0. 0. 0. 3. 4. 5. 6. 7.]