๐ 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.