CodeBlanks Logo Icon CodeBlanks

What is NumPy?

NumPy is the fundamental library for numerical computing in Python, providing multi-dimensional arrays (ndarray).

What is NumPy?

NumPy is the foundation of numerical computing in Python. At its centre is the ndarray: a multi-dimensional array that keeps numbers of the same type in contiguous memory. scikit-learn, pandas and PyTorch build their data on this structure.

import numpy as np
a = np.array([1, 2, 3])
print(a * 2)      # [2 4 6]
print(a + a)      # [2 4 6]

With a Python list, [1, 2, 3] * 2 repeats the list; in NumPy the operation is applied to every element.

Why is it fast?

NumPy's loops are written in C. Computing the whole array in one operation instead of writing a loop in Python is called vectorisation:

x = np.arange(1_000_000)
# slow: sum(v * v for v in x)
print((x * x).sum())   # fast, one line

The rule in ML code is simple: before writing a for over an array's elements, check whether NumPy has an equivalent.

Practice Vectorise

Add 20% VAT to every value in the fiyat array (multiply by 1.2) and print the result. Don't use a loop.

Starter code

model.py
import numpy as np

fiyat = np.array([100, 250, 40])

# buraya yaz

Sample solution

model.py
import numpy as np

fiyat = np.array([100, 250, 40])

print(fiyat * 1.2)

Expected output

[120. 300.  48.]

Questions and answers

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

1 What does <code>np.array([1, 2]) * 3</code> give?

  • 9
  • An error
  • [3 6] Correct answer
  • [1 2 1 2 1 2]

Explanation: NumPy operations are element-wise; each element is multiplied by 3.

2 Import NumPy under its usual short name.

Question
import numpy as ____
Answer
import numpy as np

Explanation: The community convention is the np alias; all documentation uses it.

3 Match the concepts.

Term Meaning
ndarray Multi-dimensional array
vectorization Loop-free array operation
a * 2 Element-wise multiplication
np Usual alias

All lessons in Beginner

13 Project: Classification

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