iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

NumPy Tutorial

NumPy is Python's foundation for numeric computing — fast n-dimensional arrays, vectorised math, and the bedrock for pandas, scikit-learn, PyTorch, and friends.

Install

SHELL
pip install numpy

The ndarray

PYTHON
import numpy as np

a = np.array([1, 2, 3, 4])
print(a.shape)         # (4,)
print(a.dtype)         # int64
print(a * 2)           # [2 4 6 8] — element-wise
print(a + a)           # [2 4 6 8]
print(a.mean(), a.sum(), a.std())

2D arrays — matrices

PYTHON
m = np.array([[1, 2], [3, 4]])
print(m.shape)         # (2, 2)
print(m.T)             # transpose
print(m @ m)           # matrix multiply

Creating arrays

FunctionReturns
np.zeros((3, 3))All zeros.
np.ones((3, 3))All ones.
np.arange(0, 10, 2)0, 2, 4, 6, 8.
np.linspace(0, 1, 5)Five points 0..1 inclusive.
np.random.random((3, 3))3×3 uniform random.

Why it's fast

NumPy stores data in contiguous typed buffers and dispatches to C / SIMD code. Looping in Python is slow; vectorised NumPy code on the same data is often 50–500×.

PYTHON
# Slow
result = [x * 2 for x in big_list]

# Fast
result = arr * 2          # vectorised, runs in C
Tip: "If you find yourself writing a for loop over a NumPy array, look for the vectorised version first." The slogan: let NumPy loop for you in C.

Example

Example
# import numpy as np
# a = np.array([1, 2, 3, 4])
# print(a * 2, a.mean(), a.sum())
print('NumPy adds fast n-dimensional arrays. Install with: pip install numpy')
Try it Yourself »

Exercise

Common alias for the numpy import.

import numpy as

Test yourself

Q1. NumPy's n-d array type is called…
Q2. `a * 2` on an ndarray…
Q3. Matrix multiply uses…

Discussion

Loading…