π Introduction
Accessing data is one of the most important skills when working with NumPy.
NumPy provides powerful ways to:
- Access elements
- Extract subsets
- Modify data efficiently
π’ What is Indexing?
Indexing means accessing a specific element using its position.
π§ͺ 1. Indexing in 1D Array
import numpy as nparr = np.array([10, 20, 30, 40])
print(arr[0])
π Output:
10
β Index starts from 0
π 2. Indexing in 2D Array
import numpy as nparr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr[1, 2])
π Output:
6
β Format:
arr[row, column]
πͺ What is Slicing?
Slicing means extracting a portion of an array.
βοΈ 3. Slicing in 1D Array
arr = np.array([10, 20, 30, 40, 50])
print(arr[1:4])
π Output:
[20 30 40]
β Syntax:
arr[start:end]
π 4. Slicing in 2D Array
arr = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(arr[0:2, 1:3])
π Output:
[[2 3]
[5 6]]
β Format:
arr[row_start:row_end, col_start:col_end]
π 5. Step Slicing
arr = np.array([10, 20, 30, 40, 50])
print(arr[::2])
π Output:
[10 30 50]
β Skips elements using step value
π Modifying Values
arr = np.array([10, 20, 30])
arr[1] = 99
print(arr)
π Output:
[10 99 30]
β οΈ Important Note (View vs Copy)
Slicing does not create a copy, it creates a view.
π Changing slice affects original array.
π Summary Table
| Concept | Example |
|---|---|
| Indexing | arr[0] |
| 2D Indexing | arr[1,2] |
| Slicing | arr[1:4] |
| Step | arr[::2] |
π§ Pro Tips
- Use slicing for fast data extraction
- Combine indexing + slicing for powerful queries
- Always be careful with modifying slices
π Used in Real Applications
Indexing & slicing are heavily used in:
- Pandas
- TensorFlow
- Scikit-learn
π Conclusion
Mastering indexing and slicing in NumPy gives you full control over your data.