NumPy Array Slicing
✂️ NumPy — Array Slicing
Array slicing allows you to extract a portion (subset) of an array using syntax:
-
start → Starting index (default = 0)
-
end → End index (not included)
-
step → Step size (default = 1)
✅ 1. Slicing a 1-D Array
🔄 Negative Index Slicing (Reverse)
✅ 2. Slicing a 2-D Array
Syntax:
Example:
Result:
🔹 Extracting Entire Rows or Columns
🔹 Slice Alternate Rows/Columns
Output:
✅ 3. Slicing a 3-D Array
Syntax:
Example:
🔹 Special Slicing Patterns
| Slice Expression | Meaning |
|---|---|
arr[:] |
Full array |
arr[start:] |
From index to end |
arr[:end] |
Start to index |
arr[::-1] |
Reverse array |
arr[::step] |
Take elements with step |
🧠 Key Difference: Indexing vs Slicing
| Method | Example | Returns |
|---|---|---|
| Indexing | arr[2] |
Single value |
| Slicing | arr[2:5] |
Sub-array |
📌 Summary
Slicing allows:
✔ Extracting specific rows/columns
✔ Reversing arrays
✔ Selecting elements with step size
✔ Working with multi-dimensional arrays efficiently
