NumPy Array Indexing

🔍 NumPy — Array Indexing

Array indexing in NumPy allows you to access elements of an array using their position (index).
Indexes start from 0, just like Python lists.


✅ 1. Indexing in 1-D Arrays

import numpy as np

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

print(arr[0]) # First element
print(arr[2]) # Third element
print(arr[-1]) # Last element

Output:

10
30
50

✅ 2. Indexing in 2-D Arrays

For a 2D array, indexing format is:

array[row, column]

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

print(arr2[0, 1]) # Row 0, Column 1 → 20
print(arr2[1, 2]) # Row 1, Column 2 → 60


✅ 3. Indexing in 3-D Arrays

Format:

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


🎯 Using Range Indexing (Slicing)

Indexing + slicing helps extract multiple values at once.

1-D Slicing Example:

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

print(arr[1:4]) # From index 1 to 3
print(arr[:3]) # First 3 values
print(arr[2:]) # From index 2 to end


2-D Slicing Example:

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

# Extract row 0 values from col 1 to 2
print(arr[0, 1:3])

# Extract all rows, column 1
print(arr[:, 1])


🎯 Boolean Indexing (Filter Values)

arr = np.array([10, 25, 30, 45, 60])

print(arr[arr > 30]) # Elements greater than 30


🎯 Fancy Indexing (Using Array of Indices)

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

print(arr[[1, 3, 5]]) # Fetch index 1, 3, 5

Output:

[20 40 60]

📌 Summary Table

Type Example
Single element indexing arr[2], arr2[1, 2]
Negative indexing arr[-1]
Slice indexing arr[1:4], arr[:,1]
Boolean indexing arr[arr > 50]
Fancy indexing arr[[0,2,4]]

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 *