Thuta Learning
IntermediateData & Databasesintermediate

Array Indexing

Relax. We'll talk through this in plain words — no textbook voice.

Indexing means picking out a single element from an array by its position. Just like in Python, NumPy indices start at 0. For a 2-D array, you can pick an element using the form array[row, column].

python
import numpy as np

marks = np.array([65, 78, 90, 82])
print("First mark:", marks[0])
print("Last mark:", marks[-1])

student_scores = np.array([
    [80, 75, 90],
    [88, 92, 85]
])

print("Second student, third subject:", student_scores[1, 2])

marks[0] grabs the first element. marks[-1] grabs the last one. For a 2-D array, student_scores[1, 2] grabs the second row, third column. Since indices start at 0, row 1 is actually the second row.

You should see
First mark: 65 Last mark: 82 Second student, third subject: 85

Info

Once you've got a solid handle on indexing, you can pull exactly the values you need out of table data, image pixels, or matrix values.

Easy traps

  • Calling an index beyond the array's length throws an IndexError. For example, if an array only has 4 elements, marks[4] doesn't exist.

Exercise

If an orders table has column 0 as order id, column 1 as amount, and column 2 as quantity, indexing lets you pull any cell you want directly.

python
import numpy as np

orders = np.array([
    [101, 25000, 2],
    [102, 18000, 1],
    [103, 42000, 3]
])

# First order amount
print("First order amount:", orders[0, 1])

# Last order quantity
print("Last order quantity:", orders[-1, 2])

You'll know it worked when: First order amount: 25000 Last order quantity: 3

Array Indexing | Thuta Learning