NumPy Array Slicing

✂️ NumPy — Array Slicing

Array slicing allows you to extract a portion (subset) of an array using syntax:

array[start:end:step]
  • start → Starting index (default = 0)

  • end → End index (not included)

  • step → Step size (default = 1)


✅ 1. Slicing a 1-D Array

import numpy as np

arr = np.array([10, 20, 30, 40, 50, 60])

print(arr[1:4]) # 20, 30, 40
print(arr[:3]) # From beginning → 10, 20, 30
print(arr[2:]) # Till end → 30, 40, 50, 60
print(arr[::2]) # Step = 2 → 10, 30, 50


🔄 Negative Index Slicing (Reverse)

print(arr[-4:-1]) # 30, 40, 50
print(arr[::-1]) # Reverse entire array

✅ 2. Slicing a 2-D Array

Syntax:

array[row_start:row_end, column_start:column_end]

Example:

arr2 = np.array([
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]
])
print(arr2[0:2, 1:3]) # Rows 0-1, Cols 1-2

Result:

[[20 30]
[50 60]]


🔹 Extracting Entire Rows or Columns

print(arr2[:, 1]) # All rows → column 1 → 20, 50, 80
print(arr2[1, :]) # Entire row 1 → 40, 50, 60

🔹 Slice Alternate Rows/Columns

print(arr2[::2, ::2]) # Row step 2 & Column step 2

Output:

[[10 30]
[70 90]]


✅ 3. Slicing a 3-D Array

Syntax:

array[layer, row, column]

Example:

arr3 = np.array([
[[1,2,3],[4,5,6]],
[[7,8,9],[10,11,12]]
])
print(arr3[:, 0:1, :2])


🔹 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

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *