CodeBlanks Logo Icon CodeBlanks

Array indexing

In NumPy arrays, elements are accessed by index; the first element is at index 0.

Index and slice

In a two-dimensional array you write a[row, column]. Slices work as in Python lists; : means "all":

a = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])
print(a[1, 2])     # 6
print(a[0])        # [1 2 3]  first row
print(a[:, 1])     # [2 5 8]  second column
print(a[:2, 1:])   # [[2 3] [5 6]]

In ML, taking a single feature column with X[:, 0] is very common.

Boolean mask

A condition produces a True/False array of the same size. When that array is given as an index, only the elements meeting the condition are selected:

x = np.array([5, -2, 8, -1, 3])
print(x > 0)        # [ True False  True False  True]
print(x[x > 0])     # [5 8 3]
x[x < 0] = 0        # zero the negatives
print(x)            # [5 0 8 0 3]

Several conditions are combined with & (and) and | (or); each condition must be in parentheses.

Practice Filter

Select the grades of 50 and above from the notlar array with a boolean mask and print them; then print how many there are.

Starter code

model.py
import numpy as np

notlar = np.array([45, 78, 50, 32, 91, 66])

# buraya yaz

Sample solution

model.py
import numpy as np

notlar = np.array([45, 78, 50, 32, 91, 66])

gecen = notlar[notlar >= 50]
print(gecen)
print(len(gecen))

Expected output

[78 50 91 66]
4

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 For <code>a</code> above, what is <code>a[2, 0]</code>?

  • 3
  • 8
  • 2
  • 7 Correct answer

Explanation: Third row (index 2), first column (index 0): 7.

2 Take the first column from all rows of the matrix.

Question
ilk = X[____]
Answer
ilk = X[:, 0]

Explanation: The first position selects rows (: = all), the second the column.

3 Match the expressions with what they select.

Term Meaning
a[0] First row
a[:, 0] First column
a[-1] Last row
a[a > 5] Those meeting the condition

All lessons in Beginner

13 Project: Classification

  1. Preparing data
  2. Training model
  3. Prediction
  4. Evaluation