NUMPY Tutorial



NumPy ARRAY INDEXING


🔎 NumPy Array Indexing

Indexing in NumPy works similarly to regular Python lists. It allows you to access individual elements or groups of elements from an array using their index positions.

✅ Basic Indexing

Each element in an array has an index, starting from 0.

import numpy as np

arr = np.array([10, 20, 30, 40])
print(arr[0])   # Output: 10
print(arr[2])   # Output: 30

🧮 Indexing 2D Arrays (Matrix)

In 2D arrays, indexing is done using two indices: [row, column]

arr2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr2d[0, 1])   # Output: 2
print(arr2d[1, 2])   # Output: 6

📌 Negative Indexing

You can use negative numbers to index from the end.

arr = np.array([10, 20, 30, 40])
print(arr[-1])  # Output: 40
print(arr[-2])  # Output: 30

🔢 Indexing Multiple Elements (Fancy Indexing)

You can pass a list of indices to select multiple values.

arr = np.array([10, 20, 30, 40])
print(arr[[0, 2]])  # Output: [10 30]

🎯 Indexing in 3D Arrays

Use three indices: [depth, row, column]

arr3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(arr3d[1, 0, 1])  # Output: 6

📌 Quick Tips

  • Indexing is 0-based.
  • Negative indices count from the end.
  • Use commas for multi-dimensional arrays.
Next Up: Learn about NumPy Array Slicing ➡️

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review