NumPy
A library for numerical computing, providing the
ndarraytype.
- An
ndarrayis a fixed-size, homogeneous, multidimensional array.- All elements share the same
dtype(data type).- Shapes are fixed at creation; indexing uses comma-separated dimensions.
import numpy as np
Creation
np.array([1, 2, 3, 4]) # np-array from python list
np.array([[1, 2, 3], [4, 5, 6]]) # 2-d np-array from nested lists
np.zeros((2, 3)) # 2 rows, 3 cols, all 0
np.ones((3, 2)) # 3 rows, 2 cols, all 1
np.arange(10) # np-array from 0 to 9
np.linspace(0, 1, 5) # 5 values linearly spaced from 0 to 1
Indexing
a = np.array([10, 20, 30, 40, 50])
a[0] # first element
a[-1] # last element
a[1:4] # slice (index 1 to 3)
# 2-d indexing
b = np.array([[1, 2, 3], [4, 5, 6]])
b[0, 1] # row 0, col 1
b[:, 2] # all rows, col 2
# boolean mask
mask = a > 40
a[mask] # [50] keep only elements where mask is True
Operations
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
x + y # element-wise add
x * y # element-wise multiply
x ** 2 # element-wise square
# math functions
np.sin(x)
# folding
x.sum() # element sum
x.mean() # element mean
x.max() # largest element
x.min() # smallest element
x.argmax() # index of largest element
# shape
x.shape # dimension info
x.reshape(3, 1) # change shape
Matrix
A = np.array([[1, 2], [3, 4]])
B = np.array([[10, 20], [30, 40]])
np.dot(A, B) # matrix multiplication
A @ B # same as np.dot(A, B)
np.transpose(A) # transpose
np.linalg.inv(A) # inverse